2

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?

2
  • 2
    You may be interested in looking into the moment.js library: momentjs.com Commented Feb 16, 2015 at 18:43
  • If you are able to use an external library, take a look at @Pinal 's answer. This momentjs library will save you a lot of fussing with times. Commented Feb 16, 2015 at 18:57

2 Answers 2

1

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

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

1 Comment

@void : Without 'Z' (e.g. "2015-02-16T19:00:00Z") or without timezone, your Fiddle give different result in IE/FF/Chrome (local or UTC)... new Date(date) parsing algorithms are implementation-dependent.
1

You can using momentjs.com for formatting:

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

2 Comments

Include the at word by escaping it - moment('2015-02-16T19:00:00').format('MMMM Do [at] h:mm a');
This produces February 16th at 12PM which is incorrect, seems to be treating the date as GMT-7

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.