2

Im not particularly skilled when it comes to working with datetimes in js. I have a JSON object that has some datetime fields formatted like YYYY-MM-DDTHH:MM:SS now I have to put this in HH:mm AM/PM and I came up with:

var d = Date.parse('2013-04-17T13:05:00');
var date = new Date(d);
var hrs = date.getUTCHours();
var min = date.getUTCMinutes();
var meridian;
if(hrs > 12){
    hrs -= 12;
    meridian = 'PM';
}
else {
    meridian = 'AM';
}
if (min < 10) {
    min = "0"+min;
};
var time = hrs+":"+min+" "+meridian;

Is there a better way to accomplish this?

6
  • 3
    nope. that's about it. the JS datetime object has essentially NO output formatting capabilities built into it. Commented Jun 18, 2013 at 19:24
  • There is a .toLocaleFormat method, but alas, it only works in Firefox. You'd need to use a library if you want something easier, but unless you need to juggle timezones it's usually more efficient to just write your own formatter for your particular case. Commented Jun 18, 2013 at 19:30
  • 1
    The better way is to use a well tested date library. Moment.js is a good place to start. Commented Jun 18, 2013 at 19:34
  • 1
    ISO date parsing is not available in every JS environment. See here. Use moment.js. It works everywhere. Commented Jun 18, 2013 at 20:32
  • @MattJohnson I just realized that :( honestly I wanted to stay away from having to add another library as the app has a lot already Commented Jun 18, 2013 at 20:50

3 Answers 3

8

try moment.js, this library has a ton of functionality built in.

http://momentjs.com/

moment(String, String);
moment("12-25-1995", "MM-DD-YYYY");

"hA" is the righ format for "3PM" format

Sign up to request clarification or add additional context in comments.

2 Comments

Any time someone is using date times with Javascript, I recommend moment.js. It makes lives better.
Yes and its pretty easy to use, but also offers a lot of functionality
0

A different answer for a different approach

has some datetime fields formatted like YYYY-MM-DDTHH:MM:SS now I have to put this in HH:mm AM/PM

As you know the formatting, you can take the parts you want directly from the datetime String, avoiding the use of a Date instance or library all together.

var stamp = '2013-04-17T13:05:00',
    hrs = +stamp.slice(11, 13), // 13
    min = +stamp.slice(14, 16); //  5

then continue as before from here.

Comments

-1

This is overkill, but I recently went out of my way to make my own function just for things like this

var easyDate = (function () {
    var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        thstndrd = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'],
        toDate = function () {return new Date(Date.UTC(this.yyyy, this.MM - 1, this.dd, this.hh, this.mm, this.ss, this.ms));},
        toLocaleDate = function () {return new Date(this.yyyy, this.MM - 1, this.dd, this.hh, this.mm, this.ss, this.ms);},
        UTC = function UTC(d) {
            return {
                ms: d.getUTCMilliseconds(),
                ss: d.getUTCSeconds(),
                mm: d.getUTCMinutes(),
                hh: d.getUTCHours(),
                dd: d.getUTCDate(),
                MM: d.getUTCMonth() + 1,
                yyyy: d.getUTCFullYear(),
                dow: d.getUTCDay(),
                toDate: toDate,
                toLocaleDate: toLocaleDate
            }
        },
        easyDate = function easyDate(d) {
            var o = UTC(d);
            return {
                dd: '' + o.dd,
                th: thstndrd[o.dd % 10],
                day: days[o.dow],
                MM: '' + o.MM,
                month: months[o.MM - 1],
                year: '' + o.yyyy,
                am: o.hh < 12 ? 'a.m.' : 'p.m.',
                hh: o.hh < 10 ? '0' + o.hh : '' + o.hh,
                h: '' + (o.hh % 12 || 12),
                mm: o.mm < 10 ? '0' + o.mm : '' + o.mm,
                ss: o.ss < 10 ? '0' + o.ss : '' + o.ss,
                ms: ('00' + o.ms).slice(-3),
                UTC: o
            };
        };
    easyDate.UTC = UTC;
    easyDate.delta = function (then, now) {
        var o, p, dir = -1;
        now || (now = new Date());
        if (now >= then) o = UTC(now), p = UTC(then);
        else o = UTC(then), p = UTC(now), now = then, dir = 1;
        o.dir = dir;
        o.dow = p.dow;
        o.ms = o.ms - p.ms;
        o.ss = o.ss - p.ss;
        o.mm = o.mm - p.mm;
        o.hh = o.hh - p.hh;
        o.dd = o.dd - p.dd;
        o.MM = o.MM - p.MM;
        o.yyyy = o.yyyy - p.yyyy;
        // fix negatives
        if (o.ms < 0) --o.ss, o.ms = (o.ms + 1000) % 1000;
        if (o.ss < 0) --o.mm, o.ss = (o.ss +   60) %   60;
        if (o.mm < 0) --o.hh, o.mm = (o.mm +   60) %   60;
        if (o.hh < 0) --o.dd, o.hh = (o.hh +   24) %   24;
        if (o.dd < 0) { // months have different lengths
            --o.MM;
            now.setUTCMonth(now.getUTCMonth() + 1);
            now.setUTCDate(0);
            o.dd = (o.dd + now.getUTCDate()) % now.getUTCDate();
        }
        if (o.MM < 0)  --o.yyyy, o.MM = (o.MM + 12) % 12;
        return o;
    };
    return easyDate;
}());

And using it

var o = easyDate(new Date());
o.month + ' ' + o.dd + o.th + ', ' + o.h + ':' + o.mm + ' ' + o.am;
// "June 18th, 7:30 p.m."

If you noticed the thing called easyDate.delta in the code, yep, it supports calculating differences in time, too. If you just want to run getUTC* for everything then you have easyDate.UTC. :)

5 Comments

If you're wondering why I did it when there is moment.js, I like to know exactly what is happening, why, and only have what I need (I like Objects more than Strings). This also minifies down to 1.4 kb with closure compiler (a quarter the size of moment).
The OP asked about parsing an ISO8601 formatted string. Your code doesn't do that at all.
I understood the question Is there a better way to accomplish this? to be about formatting Date (or skipping Date entirely), not about how to convert ISO 8601 to Date.
Umm... not sure how you missed it, he said quite clearly: "I have a JSON object that has some datetime fields formatted like YYYY-MM-DDTHH:MM:SS"
@MattJohnson He also gets from YYYY-MM-DDTHH:MM:SS to a Date without error in 2 lines. Yes, it could be done in one with just a new Date('2013-04-17T13:05:00');, but he's demonstrated that he is able to parse it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.