andrewb
andrewb

Reputation: 3095

JavaScript get date and time from timestamp

I have this field as part of a web response:

datetime_local: "2015-02-16T19:00:00"

Can I extract the date and time? For instance I would like to display

February 16th at 7pm

Is this possible?

Upvotes: 2

Views: 225

Answers (2)

Alex
Alex

Reputation: 11255

You can using momentjs.com for formatting:

moment(Date.parse("2015-02-16T19:00:00")).format("MMMM Do [at] hhA");
// February 16th at 10PM

Upvotes: 1

void
void

Reputation: 36703

Use this function

function getFormattedDate(date)
{
var fortnightAway = new Date(date),
        date = fortnightAway.getUTCDate(),
        hour = fortnightAway.getUTCHours(),
        month = "January,February,March,April,May,June,July,August,September,October,November,December"
      .split(",")[fortnightAway.getUTCMonth()];

    function nth(d) {
      if(d>3 && d<21) return 'th'; // thanks kennebec
      switch (d % 10) {
            case 1:  return "st";
            case 2:  return "nd";
            case 3:  return "rd";
            default: return "th";
        }
    }

return month+" "+date+nth(date) +" at "+(hour<12?hour+"am":(hour-12)+"pm");   
}

Call it like getFormattedDate("2015-02-16T19:00:00")

Working Fiddle

Upvotes: 1

Related Questions