Get exact day from date string in Javascript

[亡魂溺海] 提交于 2019-12-07 06:07:29

问题


I have checked this SO post: Where can I find documentation on formatting a date in JavaScript?

Also I have looked into http://home.clara.net/shotover/datetest.htm

My string is: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)

And I want to convert it to dd-mm-yyyy format.

I tried using:

var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDay()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

But it gives me the result as: 1-6-2013

The getDay() value is the index of day in a week.
For Instance, If my dateString is Thu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)
it gives output as 4-6-2013

How can I get the proper value of Day?

P.S: I tried using .toLocaleString() and creating new date object from it. But it gives the same result.


回答1:


To get the day of the month use getDate():

var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();



回答2:


W3 schools suggests just building your days of the week array and using it:

var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var n = weekday[d.getDay()];

Not super elegant, but usable.




回答3:


var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

Replace getDay() with getDate().

The above will return the local date for each date part, use the UTC variants if you need the universal time.




回答4:


I think you will have to take an Array of the days & utilize it using the received index from the getDay() method.



来源:https://stackoverflow.com/questions/17038105/get-exact-day-from-date-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!