Question

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

/Date(1379142000000-0700)/ 

I would like to convert unix times to this format using javascript. I've seen this function for moment.js but this dosn't return the unix/epoch formatting and it's in the wrong direction.

How can I convert unix timestamp to .net time formatting with javascript?

solutions using moment.js are good, and bonus points for converting from .net to unix as well.

Était-ce utile?

La solution

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). So presuming that the UNIX time value is UTC and that the ".NET" time string is a local time value with offset, then:

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(v)); // 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).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top