简体   繁体   中英

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

A Datetime Parse Error Occur in Server which is not in localhost,may because of difference in timezone on localhost and Server , Code : I am trying 24 hr time format to 12 hr(With AM and 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 

You should use invariant culture (if you don't need to convert to your timezone of course)

    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 

and it'l be ok in Indian culture.

Your parsing string is missing a colon.

Your composed time string is of format HH:mm while you try to parse a string composed of HHmm . That will not work.

Also remove the second h from the output format string if you want single digit hours to happen. Otherwise the output will be 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)

Convert your localtime to UTC time

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

Get Timezone information from zone name. Get Zone name from here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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