繁体   English   中英

无法将字符串识别为有效的DateTime。 :仅服务器错误

[英]String was not recognized as a valid DateTime. : Error only in Server

不在本地主机中的服务器中发生日期时间解析错误,可能是由于本地主机和服务器上的时区不同,代码:我正在尝试将24小时时间格式设置为12小时(使用AM和PM)

 string timesx2 = hr2[0]+":" + hr2[1];  //     19:22
 string s2 = DateTime.ParseExact(timesx2, "HHmm", CultureInfo.CurrentCulture)
    .ToString("hh:mm tt"); // output in localhost is: 7.22 PM 

您应该使用不变的区域性(当然,如果您不需要转换为时区)

    string timesx2 =hr2[0] + ":" + hr2[1];  //     19:22
    string s2 = DateTime.ParseExact(timesx2, "HH:mm", CultureInfo.InvariantCulture).ToString("hh:mm tt", CultureInfo.InvariantCulture); // output in localhost is: 7.22 PM 

在印度文化中也可以。

您的解析字符串缺少冒号。

当您尝试解析由HHmm组成的字符串时,您组成的时间字符串的格式为HH:mm 那不管用。

如果希望发生一位数的小时,也请从输出格式字符串中删除第二个h 否则,输出将为07:22 PM。

 string timesx2 = hr2[0]+":" + hr2[1];  //     19:22
 string s2 = DateTime.ParseExact(timesx2, "HH:mm", CultureInfo.InvariantCulture)
    .ToString("h:mm tt"); // output in localhost is: 7:22 PM 

大写字母“ H”表示24小时制,小写字母“ h”表示12小时制,将遵循候选字符串中的AM / PM。

DateTime.ParseExact("3/21/2015 8:56:04 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)

将您的当地时间转换为UTC时间

DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(localDatetime); //Convert sent datetime to UTC.

从区域名称获取时区信息。 此处获取区域名称

TimeZoneInfo zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneName);
DateTime finalDatetime = TimeZoneInfo.ConvertTime(utcTime, zoneInfo);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM