开发者

How to convert Long type datetime to DateTime with correct time zone

开发者 https://www.devze.com 2023-02-09 17:05 出处:网络
For example 1297380023295 should be 2010/2/11 9 AM I use this code right now long dateNumber = num; long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;

For example 1297380023295 should be 2010/2/11 9 AM I use this code right now

        long dateNumber = num;
        long beginTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
        DateTime dateValue = new DateTime(beginTicks + da开发者_如何学运维teNumber * 10000);

        return dateValue;

The result of this function is 1 AM,It is GMT. What can I do with it?


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();


long a= 634792557112051692;
//a= ticks time
  DateTime dt = new DateTime(a);
   Response.Write(dt.Hour.ToString());


//dt.hour convert time ticks to time hour


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());


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;


Powershell script piece, just FYI

$minDate = New-Object "System.DateTime"
$minDate = $minDate.AddYears(1969)
$minDate.AddMilliseconds(1446616420947)
0

精彩评论

暂无评论...
验证码 换一张
取 消