简体   繁体   中英

How to get the current date time of thailand using C#

I am creating an app for thailand using Xamarin form. There I need to fetch the current date time of thailand. As I am developing the app from India, my api calls (which are dependent on Datetime) are getting failed. I am trying to get the current datetime of Thailand. I have tried using Culture info but it is returning me the date in Buddhist calendar and time is not correct. My requirement is to get the time in following format. 20190602 15:50:51

var info = TimeZoneInfo.FindSystemTimeZoneById("SE Asia Standard Time");
DateTimeOffset localServerTime = DateTimeOffset.Now;
DateTimeOffset localTime = TimeZoneInfo.ConvertTime(localServerTime, info);

Then format however you need

According to this and this Microsoft documentation Articles it should work

var now = DateTime.UtcNow;
try
{
   var thaiZone = TimeZoneInfo.FindSystemTimeZoneById("SE Asia Standard Time");
   var thaiTime = TimeZoneInfo.ConvertTimeFromUtc(now, thaiZone);
   Console.WriteLine("The date and time in SE Asia Standard Time is {0} {1}", thaiTime, thaiZone.IsDaylightSavingTime(thaiTime) ? thaiZone.DaylightName : thaiZone.StandardName);
}
catch (TimeZoneNotFoundException)
{
   Console.WriteLine("The registry does not define the SE Asia Standard Time zone.");
}                           
catch (InvalidTimeZoneException)
{
   Console.WriteLine("Registry data on the SE Asia Standard Time zone has been corrupted.");
}

Where thaiTime is the current time in Thailand (SE Asia Standard Time)

There are two different time zone standards (well, not really standards , but de facto implementations):

  • The Microsoft Windows time zone data. The identifier for Thailand is "SE Asia Standard Time" .

  • The IANA time zone database . The identifier for Thailand is "Asia/Bangkok" .

The TimeZoneInfo object uses time zones defined by the operating system it is running on, hence the method name TimeZoneInfo.Find System TimeZoneById . Since you're running on Android, not Windows, your OS likely uses the IANA IDs thus:

TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Asia/Bangkok");
DateTime nowInThailand = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);

Lastly, if you need to write your code such that it works cross-platform, then consider using my TimeZoneConverter library.

TimeZoneInfo tz = TimeZoneConverter.TZConvert.GetTimeTimeZoneInfo("Asia/Bangkok");
DateTime nowInThailand = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);

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