首页 > 解决方案 > 我想在 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: '字符串未被识别为有效的日期时间。'

标签: c#datetime

解决方案


如果您与您一起工作,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"));

但是,您似乎正在使用DataReaderdr[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")); 

推荐阅读