Reading the installation date of the C# OS - c#

With the C# Core 3.1 WinForms application, the first installation date of the operating system cannot be read through regedit. It gives different results than the date given by "SystemInfo" command with CMD.
CMD "System Info":
CMD Image
Original Install Date: 11/26/2022, 1:08:26 PM
C# Read a "Regedit InstallDate(DWord)":
Regedit Image
Date: "1.01.1601 00:02:46"
C# Read a Date
RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, computerName);
key = key.OpenSubKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);
if (key != null)
{
DateTime installDate =
DateTime.FromFileTimeUtc(
Convert.ToInt64(
key.GetValue("InstallDate").ToString()));
return installDate;
}
return DateTime.MinValue;

The value in InstallDate is not a FILETIME value, but a Unix Time (seconds since 1970-01-01).
You can use
var installDate = DateTimeOffset.FromUnixTimeSeconds(regValue);
to convert to a DateTimeOffset.
For other conversion methods see How do you convert epoch time in C#?

#KlausGutter's answer is spot on, the value in the registry is a Unix time. If you want to convert it to a DateTime rather than a DateTimeOffset, then you could use something like
var installDate = DateTime.UnixEpoch.AddSeconds(regValue)

You can use this method for Converting UnixTime or whatever it is :
public static DateTime FromDate(string SerialDate)
{
var year = Convert.ToInt32(SerialDate.Substring(0, 4));
var mon = Convert.ToInt32(SerialDate[4].ToString() + SerialDate[5].ToString());
var day = Convert.ToInt32(SerialDate[6].ToString() + SerialDate[7].ToString());
try
{
var date = new DateTime(year, mon, day);
return date;
}
catch(Exception ss)
{
return DateTime.Now;
}
}

Related

How to change a past date from local Eastern time to Central European Time while accounting for daylight savings? [duplicate]

I find it hard to understand how UTC works.
I have to do the following but I'm still confused if I'd get the right result.
Objectives:
Ensure all saved dates in Database are in UTC format
Update DefaultTimezone is in Manila time
Ensure all returned dates are in Manila Time
So the code is:
public ConvertDate(DateTime? dateTime)
{
if (dateTime != null)
{
Value = (DateTime)dateTime;
TimeZone = GetFromConfig.DefaultTimeZone();
}
}
public ConvertDate(DateTime? dateTime, int GMTTimeZone)
{
if (dateTime != null)
{
Value = (DateTime)dateTime;
TimeZone = GMTTimeZone;
}
}
public int TimeZone
{
get { return m_TimeZone; }
set { m_TimeZone = value; }
}
DateTime m_Value;
public DateTime Value
{
get { return m_Value; }
set
{
m_Value = value;
DateTime converted = m_Value.ToUniversalTime().ToLocalTime();
}
}
Sample usage:
DateTime SampleInputFromUser = new DateTime(2012, 1, 22);
ConvertDate newConversion = new ConvertDate(SampleInputFromUser, 21);
DateTime answer = newConversion.Value;
Now I get confused for 'TimeZone'. I don't know how to use it to get the objectives.
Hope you understand my question and have the idea to get the objectives done.
Edit
According to #raveturned answer, I get this following code:
***Added in ConvertDate method
TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById(GetFromConfig.ManilaTimeZoneKey());
ManilaTime = TimeZoneInfo.ConvertTime(dateTime.Value, TimeZoneInfo.Local, timeInfo).ToUniversalTime();
**New Property
DateTime _ManilaTime;
public DateTime ManilaTime
{
get { return _ManilaTime; }
set { _ManilaTime = value; }
}
The .NET framework already has classes and methods available to convert DateTimes between different time zones. Have a look at the ConvertTime methods of the TimeZoneInfo class.
Edit: When you get the time to put into the database, assuming it was created with correct time zone information you can easily convert to UTC:
DateTime utcTime = inputDateTime.ToUniversalTime();
Get timeInfo as done in the question edit:
TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById(GetFromConfig.ManilaTimeZoneKey());
When you send the database time to user, convert it to the correct timezone using timeInfo.
DateTime userTime = TimeZoneInfo.ConvertTimeFromUtc(dbDateTime, timeInfo);
Personally I'd try and keep this logic separate from the propery get/set methods.
var date = System.TimeZoneInfo.ConvertTimeFromUtc(
DateTime.UtcNow,
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
TimeZoneInfo infotime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time (Mexico)");
DateTime thisDate = TimeZoneInfo.ConvertTimeFromUtc(datetimeFromBD, infotime);
To help others:
static void ChangeTimezone()
{
// Timezone string here:
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
Console.WriteLine(z.Id);
// Use one of those timezone strings
DateTime localDt = DateTime.Today;
DateTime utcTime = localDt.ToUniversalTime();
TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
DateTime estDt = TimeZoneInfo.ConvertTimeFromUtc(utcTime, timeInfo);
return;
}
For anyone facing problem in getting TimeZoneInfo in cross-platform (different time zone ids between Windows and Linux), .NET 6 addresses this issue:
Starting with this release, the TimeZoneInfo.FindSystemTimeZoneById method will automatically convert its input to the opposite format if the requested time zone is not found on the system. That means that you can now use either IANA or Windows time zone IDs on any operating system that has time zone data installed*. It uses the same CLDR mappings, but gets them through .NET’s ICU globalization support, so you don’t have to use a separate library.
A brief example:
// Both of these will now work on any supported OS where ICU and time zone data are available.
TimeZoneInfo tzi1 = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");
TimeZoneInfo tzi2 = TimeZoneInfo.FindSystemTimeZoneById("Australia/Sydney");
Find more info here
And as mentioned in other answers: to get DateTime in the desired timezone from UTC, use TimeZoneInfo.ConvertTimeFromUtc(DateTime, TimeZoneInfo) Method

Parsing dates that can have varying formats [duplicate]

I have created an API end-point. The caller may call the API with POST method passing the relevant parameters. In the parameters there is one parameter that is of datetime format.
The problem is that when calling this API the caller may passes datetime in 3 different formats:
long int - e.g. 1374755180
US format - e.g. "7/25/2013 6:37:31 PM" (as string)
Timestamp format - e.g. "2013-07-25 14:26:00" (as string)
I have to parse the datetime value and convert it to a DateTime or string in Timestamp format.
I have tried using DateTime.TryParse(), DateTime.Parse(), Convert.ToDateTime() and Convert.ToDouble() but none of them are working in certainty for me.
The required output has to be in en-GB format.
Edit:
I had thought to have an if-else if-else block to use with TryParse 3 times with one else to say the string could not be parsed. Is this the best solution? Or are there solutions better than this?
Please help!
You should consider requiring a timezone.
1 doesn't need it, but #2 and #3 do.
public DateTime ParseRequestDate()
{
// https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c
CultureInfo enUS = new CultureInfo("en-US");
var dt = "1374755180";
//var dt = "7/25/2013 6:37:31 PM";
//var dt = "2013-07-25 14:26:00";
DateTime dateValue;
long dtLong;
// Scenario #1
if (long.TryParse(dt, out dtLong))
return dtLong.FromUnixTime();
// Scenario #2
if (DateTime.TryParseExact(dt, "MM/dd/yyyy hh:mm:ss tt", enUS, DateTimeStyles.None, out dateValue))
return dateValue;
// Scenario #3
if (DateTime.TryParseExact(dt, "yyyy-MM-dd hh:mm:ss", enUS, DateTimeStyles.None, out dateValue))
return dateValue;
throw new SomeException("Don't know how to parse...");
}
EDIT
As Matt Johnson points out, DateTime.TryParseExact accepts an array of format strings.
2 & 3 could be condensed.
public DateTime ParseRequestDate()
{
// https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c
CultureInfo enUS = new CultureInfo("en-US");
var dt = "1374755180";
//var dt = "7/25/2013 6:37:31 PM";
//var dt = "2013-07-25 14:26:00";
DateTime dateValue;
long dtLong;
// Scenario #1
if (long.TryParse(dt, out dtLong))
return dtLong.FromUnixTime();
// Scenario #2 & #3
var formatStrings = new string[] { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" };
if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out dateValue))
return dateValue;
throw new SomeException("Don't know how to parse...");
}
The epoch conversion I borrowed from another question.
(An extension method)
public static class MyExtensions
{
public static DateTime FromUnixTime(this long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(unixTime);
}
}
You are looking for the DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this:
string[] formats= { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" }
var dateTime = DateTime.ParseExact("07/25/2013 6:37:31 PM", formats, new CultureInfo("en-GB"), DateTimeStyles.None);
This allows you to add as many DateTime formats to the array as you need and the method will do the conversion without the if...else statements.
If your integer is in seconds since Unix Epoch you add the number of seconds to the DateTime of the Epoch (01/01/1970) (.Net doesn't have an out of the box method for this, but the logic is seconds since 'Epoch'):
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds);
From this question.
I was facing same problem in a project where my code will run on different environments with various culture formats.
Google showed me this hidden gem. The helper function is indispensable to auto-parse datetime properly regardless of culture formats
Usage Examples:
string str = #"The last round was June 10, 2005; this time the unbroken record was held.";
DateTimeRoutines.ParsedDateTime pdt;
if (DateTimeRoutines.TryParseDate(str, DateTimeRoutines.DateTimeFormat.USA_DATE, out pdt))
Console.WriteLine("Date was found: " + pdt.DateTime.ToString());
According to the author, the code is capable of parsing various cases:
#"Member since: 10-Feb-2008"
#"Last Update: 18:16 11 Feb '08 "
#"date Tue, Feb 10, 2008 at 11:06 AM"
#"see at 12/31/2007 14:16:32"
#"sack finish 14:16:32 November 15 2008, 1-144 app"
#"Genesis Message - Wed 04 Feb 08 - 19:40"
#"The day 07/31/07 14:16:32 is "
#"Shipping is on us until December 24, 2008 within the U.S."
#" 2008 within the U.S. at 14:16:32"
#"5th November, 1994, 8:15:30 pm"
#"7 boxes January 31 , 14:16:32."
#"the blue sky of Sept 30th 2008 14:16:32"
#" e.g. 1997-07-16T19:20:30+01:00"
#"Apr 1st, 2008 14:16:32 tufa 6767"
#"wait for 07/31/07 14:16:32"
#"later 12.31.08 and before 1.01.09"
#"Expires: Sept 30th 2008 14:16:32"
#"Offer expires Apr 1st, 2007, 14:16:32"
#"Expires 14:16:32 January 31."
#"Expires 14:16:32 January 31-st."
#"Expires 23rd January 2010."
#"Expires January 22nd, 2010."
#"Expires DEC 22, 2010."
One way to deal with this problem would be setting up a factory method that "understands" different formats, and parses them accordingly.
You can create a chain of if-then-elses to deal with this problem, but you can also make a "table-driven" implementation: what you need is an array of delegates that take a string, and tell you two things:
Whether or not this delegate can parse the incoming string, and
If yes, what is the result of that parse, expressed as DateTime
Here is a sample implementation:
private static readonly DateParsers = new Func<string,Tuple<DateTime,bool>>[] {
(s) => {
long res;
if (long.TryParse(s, out res)) {
// The format was correct - make a DateTime,
// and return true to indicate a successful parse
return Tuple.Create(new DateTime(res), true);
} else {
// It does not matter what you put in the Item1
// when Item2 of the tuple is set to false
return Tuple.Create(DateTime.MinValue, false);
}
}
...
// Add similar delegates for other formats here
};
Now your factory method could be implemented as follows:
private static bool TryParseMultiformat(string s, out DateTime res) {
// Check all parsers in turn, looking for one returning success
foreach (var p in DateParsers) {
var tmp = p(s);
if (tmp.Item2) {
res = tmp.Item1;
return true;
}
}
res = DateTime.MinValue;
return false;
}
If the possible formats are fixed then you can use TryParseExact
A possible solution is to use TryParse, if it fails to get proper date then fallback to known formats and use TryPraseExact
Thanks for your answers. I tried the options suggested in couple of answers and found out a very simple approach that worked for me.
public static bool ParseDate(string dateString, out DateTime dateValue)
{
long dtLong = 0L;
bool result = false;
if (long.TryParse(dateString, out dtLong))
{
// I copied the epoch code here for simplicity
dateValue = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(dtLong);
result = true;
}
// Working for US and Timestamp formats
else if (DateTime.TryParse(dateString, out dateValue))
result = true;
return result;
}
Earlier I was trying to use TryParse for all the 3 formats which was not working.
Somehow, TryParseExact did not work for the timestamp format. It worked for the US format. That is the reason I had to write my own.
If you use TryParseExact, only G-O-D and the Microsoft developers know how many possible date time formats it will try to parse before it gives up. Perhaps a better solution is to use a quick regex and then an appropriate parser. I tried to make the regex as simple as possibke, you may have to tweak this a little
private static readonly Regex R1
= new Regex(#"^\d+$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex R2
= new Regex(#"M$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex R3
= new Regex(#"^\d{4}-", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static void Main(string[] args)
{
string[] stringDates = new[]
{
"1374755180",
"2013-07-25 14:26:00",
"7/25/2013 6:37:31 PM"
};
foreach (var s in stringDates)
{
DateTime date = default(DateTime);
if (R1.IsMatch(s))
date = new DateTime(long.Parse(s));
else if (R2.IsMatch(s))
date = DateTime.Parse(s);
else if (R3.IsMatch(s))
date = DateTime.Parse(s);
if (date != default(DateTime))
Console.WriteLine("{0}", date);
}
Console.WriteLine("Press ENTER to continue...");
Console.ReadLine();
}

Conversion display wrong data

If i take property as string that time output will properly come but i have to do it with date and time when i convert it with date and time it will show only one record with wrong date and time what should i do any Idea.
what i done in other case it working.But when i work with registry install date it's convert it into date and time but I don't get perfect date.
controllerModel.cs
private DateTime _installedOn;
public DateTime installedon
{
get { return _installedOn; }
set
{
_installedOn = value;
RaisePropertyChanged("installedon");
}
}
ControlPanelViewModel.cs
#region Methods
public void ListedSoftware()
{
string uninstallKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
Controller objct = new Controller();
objct.displayname = sk.GetValue("DisplayName").ToString();
objct.displayversion = sk.GetValue("DisplayVersion").ToString();
objct.publisher = sk.GetValue("Publisher").ToString();
objct.installedon = Convert.ToDateTime(sk.GetValue("InstallDate"));
objct.estimatedSize = sk.GetValue("EstimatedSize").ToString();
Students.Add(objct);
}
catch (Exception ex)
{ }
}
}
}
}
Looking in my registry, all of the InstallDate values seem to be in the format yyyyMMdd, where yyyy is the year, MM the month and dd the day.
To parse this string format into a DateTime object, you can use the DateTime.ParseExact method:
var timestampString = sk.GetValue("InstallDate").ToString();
var timestamp = DateTime.ParseExact(timestampString, "yyyyMMdd",
CultureInfo.InvariantCulture);
Be aware that the InstallDate value may not exist in all subkeys in that part of the registry, so you will need to take that into account.
You can also use DateTime.Parse(), this one is work wor me.
CultureInfo provider = CultureInfo.InvariantCulture;
objct.installedon = DateTime.Parse(sk.GetValue("InstallDate").ToString(), provider);
Btw, I got a similar result (01010001) when sk.GetValue("InstallDate") was null.
Perhaps, Convert.ToDateTime(string) uses invalid format to parse your registry entry. You should experiment with your date format with Convert.ToDateTime(String, IFormatProvider) method. Here's good example on msdn with CultureInfo. Prehaps, CultureInfo.CurrentCulture will work for you

Want to display date and time based on timezone id Nodatime [duplicate]

This question already has answers here:
How Convert UTC Date & time to local time using different timezone Nodatime
(2 answers)
Closed 8 years ago.
I heard that if I use nodatime library then I can get date & time based on timezone id.
first I change my pc date and time. set to old date and time in my pc and then run the below code which disappoint me.
using NodaTime;
var zoneId = "Asia/Kolkata";
DateTimeZone _zone = DateTimeZoneProviders.Tzdb[zoneId];
ZonedDateTime _now = SystemClock.Instance.Now.InZone(_zone);
var xx = _now.LocalDateTime;
Below code display wrong date & time because I set my pc date & time to few days back.
Is there any way that if date & time is wrong but still code display right date & time without depending on user pc date & time setting using Noda Time library. Looking for suggestion.
UPDATE
i follow this way but not sure am i on right tract to achieve my goal.
public static DateTime GetFastestNISTDate()
{
var result = DateTime.MinValue;
DateTime utcDateTime= DateTime.MinValue;
// Initialize the list of NIST time servers
// http://tf.nist.gov/tf-cgi/servers.cgi
string[] servers = new string[] {
"nist1-ny.ustiming.org",
"nist1-nj.ustiming.org",
"nist1-pa.ustiming.org",
"time-a.nist.gov",
"time-b.nist.gov",
"nist1.aol-va.symmetricom.com",
"nist1.columbiacountyga.gov",
"nist1-chi.ustiming.org",
"nist.expertsmi.com",
"nist.netservicesgroup.com"
};
// Try 5 servers in random order to spread the load
Random rnd = new Random();
foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
{
try
{
// Connect to the server (at port 13) and get the response
string serverResponse = string.Empty;
using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
{
serverResponse = reader.ReadToEnd();
}
// If a response was received
if (!string.IsNullOrEmpty(serverResponse))
{
// Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
string[] tokens = serverResponse.Split(' ');
// Check the number of tokens
if (tokens.Length >= 6)
{
// Check the health status
string health = tokens[5];
if (health == "0")
{
// Get date and time parts from the server response
string[] dateParts = tokens[1].Split('-');
string[] timeParts = tokens[2].Split(':');
// Create a DateTime instance
DateTime utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
// Convert received (UTC) DateTime value to the local timezone
//result = utcDateTime.ToLocalTime();
return utcDateTime;
// Response successfully received; exit the loop
}
}
}
}
catch
{
// Ignore exception and try the next server
}
}
return result;
}
var wc = GetFastestNISTDate();
var pattern = InstantPattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
var parseResult = pattern.Parse(wc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
if (!parseResult.Success)
throw new InvalidDataException("...whatever...");
var instant = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
If you can't trust the computer's clock, then you must get the time from another source, such as from a network server via NTP connection. Noda Time does not have this functionality.
You may be interested in this answer which describes how to query an NTP server in C#. Note that at the very end of the code in that answer it calls ToLocalTime. Instead, you would use Noda Time's Instant.FromDateTimeUtc method.

What is the best way to get a formatted string to represent UTC offset? [duplicate]

This question already has answers here:
How to control appearance of ':' in time zone offset when parsing/formatting Datetime
(4 answers)
Closed 4 years ago.
I need to format a date like so: 20110202192008-0500. The following code does the trick but I was wondering if there is a better/cleaner way to do this in c# 3.5. Thanks!!
var date = DateTime.Now;
var strDate = TimeZoneInfo.ConvertTimeToUtc(date).ToString("yyyyMMddHHmmss");
var offsetHours = TimeZoneInfo.Local.GetUtcOffset(date).Hours.ToString("00");
var offsetMinutes = TimeZoneInfo.Local.GetUtcOffset(date).Minutes.ToString("00");
Console.Write(string.Concat(strDate, offsetHours, offsetMinutes));
How about this:
.NET 4
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Console.WriteLine(DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));
.NET 3.5
var utcAlmostFormat = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
var utcFormat = System.Text.RegularExpressions.Regex.Replace(utcAlmostFormat, #"(\d\d):(\d\d):(\d\d)",#"$1$2");
Console.WriteLine(utcFormat);
Go Steelers (from a guy in the Strip)
If you have a DateTimeOffset, the custom specifier zzz will output the timezone offset, though in the more standard "+HH:mm" format. If you don't want the colon, a string replace will do the trick.
Debug.WriteLine(DateTimeOffset.Now.ToString("yyyyMMddHHmmsszzz").Replace(":", ""));
// Result: "20110202153631-0500"
Here are some extension methods that will work in both .Net 3.5 and .Net 4.0 that will do exactly what you are asking in a very straight-forward way:
public static string ToStringWithOffset(this DateTime dt)
{
return new DateTimeOffset(dt).ToStringWithOffset();
}
public static string ToStringWithOffset(this DateTime dt, TimeSpan offset)
{
return new DateTimeOffset(dt, offset).ToStringWithOffset();
}
public static string ToStringWithOffset(this DateTimeOffset dt)
{
string sign = dt.Offset < TimeSpan.Zero ? "-" : "+";
int hours = Math.Abs(dt.Offset.Hours);
int minutes = Math.Abs(dt.Offset.Minutes);
return string.Format("{0:yyyyMMddHHmmss}{1}{2:00}{3:00}", dt, sign, hours, minutes);
}
You can now call these on any DateTime or DateTimeOffset you wish. For example:
string s = DateTime.Now.ToStringWithOffset();
or
string s = DateTimeTimeOffset.Now.ToStringWithOffset();
or
TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(someDate);
string s = someArbitraryTime.ToStringWithOffset(offset);
or any other number of ways you can think of.
We found that DateTimeOffset.ToString("o") is best for that. Example:
DateTime.UtcNow.UtcToDateTimeOffset(User.GetTimeZone()).ToString("o");
If you need to convert from DateTime, use helper method like:
/// <summary>Converts from a UTC DateTime to the user's local DateTime</summary>
/// <param name="utcDateTime">UTC DateTime</param>
/// <param name="timeZoneInfo">The time zone info.</param>
/// <returns>The DateTime in the user's time zone</returns>
public static DateTimeOffset UtcToDateTimeOffset(this DateTime utcDateTime, TimeZoneInfo timeZoneInfo = null)
{
if (utcDateTime.Kind != DateTimeKind.Utc)
{
throw new InvalidTimeZoneException("Converting UTC to Local TimeZone, but was not UTC.");
}
DateTimeOffset dto = new DateTimeOffset(utcDateTime, TimeSpan.Zero);
return timeZoneInfo.IsNotNull() ? dto.ToOffset(timeZoneInfo.GetUtcOffset(dto)) : dto;
}
You can use one of the DateTime Standard Formats or create a Custom Format.
// Round-trip date/time pattern: "O", "o"
DateTime.Now.ToString("o") // "2018-01-15T11:00:50.5604578-05:00"
DateTime.UtcNow.ToString("o") // "2018-01-15T16:00:50.5604578Z"
// Universal sortable date/time pattern: "u"
DateTime.Now.ToString("u") // "2018-01-15 16:00:50.5604578Z"
DateTime.UtcNow.ToString("u") // "2018-01-15 16:00:50.5604578Z"
// Custom format
DateTime.Now.ToString("yyyyMMddHHmmssK") // "20180115160050-05:00"
DateTime.UtcNow.ToString("yyyyMMddHHmmssK") // "20180115160050Z"
Try to use
var date = DateTimeOffset.Now;
var timestamp = $"{date:yyyy-MM-dd'T'HH:mm:ss.fff}{date.Offset.Ticks:+;-;}{date.Offset:hhmm}";
... or something like this.
I think there are a lot of ways, for example:
var offset = TimeZoneInfo.Local.BaseUtcOffset;
string result = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + offset.Hours.ToString("00") + offset.Minutes.ToString("00");

Categories

Resources