Skip to content Skip to sidebar Skip to footer

Convert Dates String To Different Format With Javascript

This is what I have in a script that is pulling events with a Google Calendar API: var datestring2 = (startJSDate.getMonth() + 1) + '/' + startJSDate.getDate(); After I append thi

Solution 1:

There is no built in function in Javascript that can do that (I presume you are after something like PHP's date() function).

You can certainly roll your own solution as other answers have suggested, but unless you are really against it, date.js is great for this.

You can use the libraries toString() function to get formatted date strings like so:

Date.today().toString("d-MMM-yyyy");

More information can be found in the DateJS API documention.


Solution 2:

You need something like:

var months = ['January', 'February', 'March', ...];
var ordinals = {1:'st', 21:'st', 31:'st', 2:'nd', 22:'nd', 3:'rd', 23:'rd'};  
var m = startJSDate.getMonth();
var d = startJSDate.getDate();
var s = months[m] + ', ' + s + (ordinals[s] || 'th');

Solution 3:

This article has some great examples on printing out dates in javacript

And from there you want something like this

var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");

var m_names = new Array("January", "February", "March", 
 "April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
    sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
    sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
    sup = "rd";
}
else
{
   sup = "th";
}

var curr_month = d.getMonth();
var curr_year = d.getFullYear();

datestring2 = d_names[curr_day] + ", " + m_names[curr_month] + " " + curr_date + sup );

Will give you Thursday, December 1st


Post a Comment for "Convert Dates String To Different Format With Javascript"