Convert dates string to different format with java

2019-07-30 03:13发布

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 this to a list it prints out in the format 12/2 while I want it to print out Friday, Dec 2.

How can I do this? I have looked into date.js but had no luck.

3条回答
老娘就宠你
2楼-- · 2019-07-30 03:29

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.

查看更多
贼婆χ
3楼-- · 2019-07-30 03:34

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

查看更多
霸刀☆藐视天下
4楼-- · 2019-07-30 03:39

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');
查看更多
登录 后发表回答