How to convert Long type datetime to DateTime with correct time zone
92,836
Solution 1
You're looking for the ToLocalTime()
method:
long unixDate = 1297380023295;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date= start.AddMilliseconds(unixDate).ToLocalTime();
Solution 2
long a= 634792557112051692;
//a= ticks time
DateTime dt = new DateTime(a);
Response.Write(dt.Hour.ToString());
//dt.hour convert time ticks to time hour
Solution 3
You can specify the DateTimeKind when you create a new DateTime object, so you could specify that as UTC and then use .ToLocalTime to convert it to local time:
long dateNumber = 1297380023295;
long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
DateTime dt = new DateTime(beginTicks + dateNumber * 10000, DateTimeKind.Utc);
MessageBox.Show(dt.ToLocalTime().ToString());
Solution 4
U can use static
methods from DateTimeOffset
.
DateTimeOffset.FromUnixTimeSeconds()
DateTimeOffset.FromUnixTimeMilliseconds()
Depends in wich format you have your ticks.
and if u want DateTime
you can use for example
var ticks = 1635091250;
var dateTime = DateTimeOffset.FromUnixTimeSeconds(ticks).DateTime;
Solution 5
Powershell script piece, just FYI
$minDate = New-Object "System.DateTime"
$minDate = $minDate.AddYears(1969)
$minDate.AddMilliseconds(1446616420947)
Author by
Shisoft
Studies in Donghua University Founder of Shisoft,A web service integrate team.
Updated on October 25, 2021Comments
-
Shisoft over 2 years
For example
1297380023295
should be 2010/2/11 9 AM I use this code right nowlong dateNumber = num; long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks; DateTime dateValue = new DateTime(beginTicks + dateNumber * 10000); return dateValue;
The result of this function is 1 AM,It is GMT. What can I do with it?