0

I am making a GET request to a web api on a different server to get a C# DateTime object. I want its formatting to stay in the C# format like:

6/11/2014 6:46:43 PM

However, the formatting gets changed once I retrieve it in my javascript function like this:

2014-06-11T18:46:43.2730485Z

How do I preserve the formatting, or how do I convert it back to the original format?

SKLAK
  • 3,825
  • 9
  • 33
  • 57
  • 4
    There's no "C# format" - what you're seeing is the default format for your particular `CultureInfo`. Note that a `DateTime` value doesn't *have* a format - it just depends on how you render it. Now, I'd *strongly* recommend that for machine-to-machine communication, you use the ISO-8601 format from your second example. It's the most common standard for date/time serialization, and it doesn't have culture implications. (Your date looks like November 6th to me, as a UK person...) – Jon Skeet Jun 13 '14 at 22:00
  • 2
    Alright. Btw though, I managed to fixed the issue sending the datetime as a string. Either ways, I'll take your advice and try to work with the ISO-8601 format – SKLAK Jun 13 '14 at 22:01
  • 1
    related: http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – vimes1984 Jun 13 '14 at 22:05

1 Answers1

0

You could create a Date object, and then build a string from it.

var d = new Date(returnedDate);

var month = d.getMonth() + 1, // month indexed from 0-11
    day = d.getDate(),
    year = d.getFullYear(),   // use instead of getYear() for 4-digit year
    hour = d.getHours(),
    minute = d.getMinutes(),
    second = d.getSeconds();

// Convert to 12-hour time, if that's your thing
if (hour >= 12) {
    hour -= 12;
    var meridiem = 'AM';
    // Correct for midnight
    if (hour === 0) hour = 12;
} else {
    var meridiem = 'PM';
}

var dStr = month + '/' + day + '/' + year + ' ' +
           hour + ':' + minute + ':' + second + ' ' + meridiem;

I'm unfamiliar with C#'s conventions for dates, but that looks pretty close to what you want. Note that this will interpret the time in the local timezone. Normalizing that mostly requires using the UTC methods for the Date object.

Being real here: JavaScript's date libraries are... lacking. I really do recommend using a library for this. I like Moment.js a lot. Read up on parsing a date string and formatting a date for display.

Cole Kettler
  • 481
  • 4
  • 11