c# - 我想在 C# 中将日期“2018-05-18 17:16:24.570”转换为“7/26/2018, 10:42 AM”格式
问题描述
我正在string
从数据库中检索日期,然后需要对其进行转换。这样以不同的格式打印。我在用
string date = dr[2].ToString();
date = DateTime
.ParseExact(date,"yyyy-MM-dd hh:mm:ss.fff tt ",new CultureInfo.InvariantCulture("enUS"));
但这不起作用:
System.FormatException: '字符串未被识别为有效的日期时间。'
解决方案
如果您与您一起工作,string
则可以在ParseExact
后面加上ToString
:
string date = "2018-05-18 17:16:24.570";
// 5/18/2018 05:16 PM
date = DateTime
.ParseExact(date, "yyyy-M-d H:m:s.fff", CultureInfo.InvariantCulture)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
但是,您似乎正在使用DataReader
(dr[2]
片段);如果是您的情况,Convert
则比ParseExact
(假设 RDBMS 具有相应Date
字段)更好的选择:
string date = Convert
.ToDateTime(dr[2])
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
编辑:如果您想将时间从 UTC 更改为 TimeZone,您可以尝试(在此处TimeZoneInfo
查看所有可用时区),例如
//TODO: Put the right Time Zone Id here
// Or should it be "Arabian Standard Time"? I've tried to guess
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
string date = TimeZoneInfo
.ConvertTimeFromUtc(Convert
.ToDateTime(dr[2]), zone)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
推荐阅读
- jquery - Backbone.js 从 0.9.2 到 0.9.9,出现错误“Uncaught ReferenceError: index is not defined”
- performance - 是否可以在运行时更改 Spark 参数?
- php - 存储基于日期的可用性的最有效方法是什么
- python - Pandas - 保留与其他数据框中的两个单元格匹配的行
- excel - 如何从不同的工作表中获取查找值并显示适当的结果?
- c - 生成 32 字节随机数据范围内的随机数,无需 bignum 库
- jquery - 遍历父元素并使用 ($this) 转到其所有子元素
- css - 如何让 FlexBox 元素与 SVG 元素重叠?
- xamarin.android - 如何从 Task.Run(Xamarin.Android) 中的函数获取返回结果?
- python - Pandas - 识别项目的最后一个条目