在不更改原始字符串格式的情况下将字符串转换为 DateTime c#

Convert string to DateTime without changing the original string 's format c#

我正在从保存在服务器上的 MySQL 数据库 table 读取日期时间,以使用查询 "Select Now()" 获取当前服务器日期时间。我得到了日期时间。

var tmpString = DateTime.Parse(reader[0].ToString()).ToString("yyyy-MM-dd hh:mm:ss tt");
DateTime result = Convert.ToDateTime(tmpString);

reader[0] 包含我服务器的当前日期时间。 tmpString 的值为“2017-04-06 03:10:20 PM”

结果包含以下格式的日期时间: 06-Apr-17 3:10:20 下午(我机器的日期时间格式)

但我希望日期时间符合我的服务器日期时间格式 ("yyyy-MM-dd hh:mm:ss tt")

我试过使用

DateTime result = DateTime.ParseExact(tmpString, "yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);

这也 returns 2017 年 4 月 6 日 3:16:11 下午。

您可以直接使用如下:

result.ToString("yyyy-MM-dd HH':'mm':'ss")

这应该有效。

可能会有所帮助

        System.Globalization.CultureInfo customCulture = new System.Globalization.CultureInfo("en-US", true);

        customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

        System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
        System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

        DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));