简体   繁体   中英

Converting a datetime to a particular timezone but in a specific format c#

I am not entirely sure if this is even possible and I have tried a number of things, short of writing an algorithm.

I have a variable of type datetime which I want to convert into a specific timezone and into a specific format. Let me give an example

todayCloseLine -> UTC time -> "2021-05-25 18:36:00"

closeline_local -> converting todayCloseLine to GMT Standard Time -> "2021-05-25 19:36:00"

I was able to convert to the given timezone so no problems with that. What I want is this format for closeline_local

2021-05-25T18:36:00.0000000+01:00

What I tried is as below (amongst other things):

  • tried ToLocalTime().ToString("o") on todayCloseLine but for this to work my machine should be on the specific timezone. This is not an option

Now, what I can do is write an algorithm as follows:

  • get the difference in timespan depending on which one is greater
  • get the sign, + or - depending on which one is greater
  • then convert todayCloseLine to ToString("o") and append the sign and timespan to get the final output

But I want to avoid this and preferably use an inbuilt method or something to get this conversion

Please if you can help. Thanks in advance.

EDIT

These are the tries I have done. I tried permutations combinations in this but no luck

DateTime todayCloseLine1 = DateTime.SpecifyKind(Convert.ToDateTime("25-May-2021 18:36"), DateTimeKind.Utc);
var closeline_local1 = DateTime.SpecifyKind(TimeZoneInfo.ConvertTime(
todayCloseLine1,
TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time")), DateTimeKind.Local);
var dt1 = closeline_local1.ToLocalTime().ToString("o");

var dt2 = closeline_local1.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffzzz");

OUTPUT for both dt1 and dt2 - 
2021-05-25T19:36:00.0000000+05:30 --> machine date IST
2021-05-25T19:36:00.0000000+01:00 --> machine date LONDON

Hope this helps

use DateTimeOffset to format the string in desired format

DateTime close_line_UTC = DateTime.SpecifyKind(Convert.ToDateTime("25-May-2021 18:36"), DateTimeKind.Utc);
var myTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
var closeline_local = TimeZoneInfo.ConvertTimeFromUtc(close_line_UTC, myTimeZone);
TimeSpan utcOffsett = myTimeZone.GetUtcOffset(closeline_local);
DateTimeOffset dateTimeOffset = new DateTimeOffset(closeline_local, utcOffsett);          
var closeline_local_formatted = dateTimeOffset.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffzzz");

References

  1. DateTime.ToString Method

  2. DateTimeOffset.ToString Method

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