简体   繁体   English

在javascript中将unix时间戳转换为.NET日期时间

[英]Converting unix timestamp to a .NET Date Time in javascript

I'm interfacing with an api and they use .NET so all of my time stamps need to conform to .NET 's Date Time format which looks something like this我正在与一个 api 接口,他们使用.NET所以我所有的时间戳都需要符合.NET的日期时间格式,它看起来像这样

/Date(1379142000000-0700)/ 

I would like to convert unix times to this format using javascript .我想使用javascript将 unix 时间转换为这种格式。 I've seen this function for moment.js but this dosn't return the unix/epoch formatting and it's in the wrong direction.我已经在moment.js 中看到了这个函数,但这不会返回 unix/epoch 格式,而且方向错误。

How can I convert unix timestamp to .net time formatting with javascript?如何使用 javascript 将unix时间戳转换为.net时间格式?

solutions using moment.js are good, and bonus points for converting from .net to unix as well.使用moment.js解决方案很好,并且从.net转换到 unix 也有奖励积分。

If you have a date object, it seems like you need the UTC millisecond time value and the timezone offset in hours and minutes (hhmm).如果您有一个日期对象,似乎您需要 UTC 毫秒时间值和以小时和分钟 (hhmm) 为单位的时区偏移量。 So presuming that the UNIX time value is UTC and that the ".NET" time string is a local time value with offset, then:因此,假设 UNIX 时间值是 UTC 并且“.NET”时间字符串是带有偏移量的本地时间值,那么:

 function unixTimeToDotNetString(v) { // Simple fn to add leading zero to single digit numbers function z(n) { return (n < 10 ? '0' : '') + n; } // Use UNIX UTC value to create a date object with local offset var d = new Date(v * 1e3); // Get the local offset (mins to add to local time to get UTC) var offset = d.getTimezoneOffset(); // Calculate local time value by adding offset var timeValue = +d + offset * 6e4; // Get offset sign - reverse sense var sign = offset < 0 ? '+' : '-'; // Build offset string as hhmm offset = Math.abs(offset); var hhmm = sign + z(offset / 60 | 0); hhmm += z(offset % 60); // Combine with time value return timeValue + hhmm; } var unixTime = 1393552984; console.log(unixTime + ' : ' + unixTimeToDotNetString(unixTime)); // 1393552984 : 1393517104000+1000

The difference between the two time values shoudl be equivalent to the offset in milliseconds (in this case where the timezone is UTC+1000 it's 36000000).两个时间值之间的差异应该等于以毫秒为单位的偏移量(在这种情况下,时区是 UTC+1000,它是 36000000)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM