简体   繁体   中英

Get timestamp incl. timezone with datetime.now()

I use a software where they generate time and date for records, like:

20200110T091352+0100

Now I need to generate similar date format in C#

What I can figure out from the time stamp is:

  • 2020 :year
  • 01 :month
  • 10 :day
  • T091352 :?? microseconds?
  • +0100 : timezone

What I got so far:

DateTime.Now.ToString("yyyyMMdd")

Thanks for any hints that point me in the right direction.

20200110T091352+0100

This is the ISO 8601 Basic Format for a "complete representation" with offset. It is defined in ISO 8601:2004(E) section 4.3.2.

It may look odd, because often when people talk about ISO 8601, they mean the Extended Format , which for your example would be 2020-01-10T09:13:52+01:00 . Both formats (and others) are part of the ISO 8601 specification.

The T091352 represents the time of day, 09:13:52. The +0100 indicates the time zone offset for that local time. In other words, 09:13:52 was 1 hour ahead of UTC (which would be 08:13:52 for that same moment in time).

You can best get the current time in this format from .NET as follows:

DateTimeOffset now = DateTimeOffset.Now;
string formatted = now.ToString("yyyyMMddTHHmmsszzz", CultureInfo.InvariantCulture).Remove(18,1);

Working .NET Fiddle here.

The .Remove(18,1) takes the colon ( : ) out of the offset string produced by the zzz format specified. Unfortunately, .NET doesn't have a format specifier for an offset showing both hours and minutes that doesn't include the colon. You could get the same results with .Replace(":","") if you prefer.

Also note that I used DateTimeOffset instead of DateTime , because you want the offset to always show in the response correctly. zzz isn't recommended for DateTime values per the notes in the docs , and while K would work for DateTime.Now , it wouldn't necessarily be consistent for other values because it depends on the .Kind property. If you must use DateTime , use K rather than zzz , but check the .Kind carefully.

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