3

I have a function which works well, for converting dates from a webservice returned in json format. The webservices gives dates in the following type of format:

Data example: The dates look like this in the json data

\/Date(1373875200000)\/

Current function: This is the current function I have

function HumanDate(date) {

    var jsondateString = date.substr(6);
    var current = new Date(parseInt(jsondateString));
    var month = current.getMonth() + 1;
    var day = current.getDate();
    var year = current.getFullYear();
    var hour = current.getHours();
    var minute = current.getMinutes();
    var datetime = day + "/" + month + "/" + year + " " + hour + ":" + minute

    return datetime;

}

Usage: This is how I use the function above

success: function(data) {

    if (data.d[0]) {
        $.each(data.d, function(index, data) {

            $("body").append(HumanDate(data.from) + '<br />');

        });
    } else {

Current output: This is the output I currently get, notice the missing 0's

2/7/2013 9:0
15/7/2013 9:30
15/10/2013 10:0
15/11/2013 10:30

Expected output: This is the output I would like, notice the extra 0's

02/07/2013 09:00
15/07/2013 09:30
15/10/2013 10:00
15/11/2013 10:30

Question:

How do I get the date and time formatted as the Expected output examples?

oshirowanen
  • 15,297
  • 82
  • 198
  • 350
  • http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript – WWW Aug 01 '13 at 14:30
  • There is no code that would add the leading zeroes - I don't see how you can expect them then. :P – Esailija Aug 01 '13 at 14:31
  • @Esailija lots of languages provide ways to customize the output format for dates, so i assume the asker is wondering if there's something similar in javascript. (unfortunately there's not) – user428517 Aug 01 '13 at 15:22

3 Answers3

4

If you don't use a library, then you have to do some work, that is you have to put the "0" yourself.

Instead of simply concatenating day, you need to concatenate

(day<10 ? '0'+day : day)

and the same for the other fields.

But note that there are good javascript libraries filling this kind of gap. I personally used datejs for date manipulations.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Good one. Very similar to the approach used in Mozilla's Date Javascript Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Example.3A_ISO_8601_formatted_dates – itorres Aug 01 '13 at 14:38
  • 1
    This is fine, but regarding datejs, please realize that it [has been abandoned](http://stackoverflow.com/tags/datejs/info). – Matt Johnson-Pint Aug 01 '13 at 14:50
  • @MattJohnson Good observation. While it still works very well for the project in which I use it, I'll stop recommending it. – Denys Séguret Aug 01 '13 at 14:52
  • That sounds like a good plan. I have also heard others that still use it without problems, but then they probably just aren't using the parts that have issues. Still, you may want some unit tests around your code that uses it, just to be sure. – Matt Johnson-Pint Aug 01 '13 at 14:59
2

I'd suggest using a library for this kind of thing -- something like Moment.js would do the job perfectly (and give you a load more functionality like date addition/subtraction into the bargain).

With moment.js, your code could look like this:

function HumanDate(date) {
    return moment(date).format('MM/DD/YYYY HH:mm');
}

usage example:

alert(HumanDate("\/Date(1373875200000)\/"));
//alerts "07/15/2013 09:00"

Hope that helps.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • What's the purpose of the X? – oshirowanen Aug 01 '13 at 14:46
  • Great answer. But if you take off the `X` formatter, Moment.js will accept the original string that he provided. See [these docs](http://momentjs.com/docs/#/parsing/asp-net-json-date/). – Matt Johnson-Pint Aug 01 '13 at 14:48
  • 1
    @MattJohnson - cool, I've removed the `X` from the answer. I wasn't aware of it having a specific ASP formatter. (The `X` was there to force it to accept the date as a timestamp; the docs say it's best to specify the format to avoid cross browser issues) – Spudley Aug 01 '13 at 14:52
  • Looks great now. Thanks for updating! Yeah, the docs are correct *except* for ISO8601 and the bizarre "ASP.NET Json Date" format, which are detected properly without any format string. Other formats *might* be detected without a formatter, but that depends on the browser. – Matt Johnson-Pint Aug 01 '13 at 14:54
1

You could also try moment.js. A 6.5kb library for formatting dates

var m = moment( new Date() );
m.format( "DD/MM/YYYY HH:mm");
Splendiferous
  • 733
  • 2
  • 6
  • 17