admin管理员组

文章数量:1303404

I have a Date, which I want to convert to a string, but without the time, just the date part.

My current code:

var date = new Date(2014, 9, 08); //Wed Oct 08 2014 00:00:00 GMT-0500 (Central Daylight Time) 
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};

console.log(date.toLocaleTimeString("en-US", options)); 
// output: Wednesday, October 8, 2014 12:00:00 AM 
// what I'm looking for: Wednesday, October 8, 2014

How can I modify the options to not display time?

I have a Date, which I want to convert to a string, but without the time, just the date part.

My current code:

var date = new Date(2014, 9, 08); //Wed Oct 08 2014 00:00:00 GMT-0500 (Central Daylight Time) 
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};

console.log(date.toLocaleTimeString("en-US", options)); 
// output: Wednesday, October 8, 2014 12:00:00 AM 
// what I'm looking for: Wednesday, October 8, 2014

How can I modify the options to not display time?

Share Improve this question edited Oct 1, 2014 at 16:59 isherwood 61.1k16 gold badges120 silver badges169 bronze badges asked Oct 1, 2014 at 16:48 SoluableNonagonSoluableNonagon 11.8k11 gold badges58 silver badges100 bronze badges 1
  • possible to use toDateString() as well – SoluableNonagon Commented Oct 1, 2014 at 16:55
Add a ment  | 

2 Answers 2

Reset to default 10

Juste use toLocaleDateString instead of toLocaleTimeString and you should get the result you are expecting :

var date = new Date('2014', '9', '08'); //Wed Oct 08 2014 00:00:00 GMT-0500 (Central Daylight Time)
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
console.log(date.toLocaleDateString("en-US", options)); 

returns : "Wednesday, October 8, 2014"

I will also second the above poster and remend using moment.js; it is lightweight and very flexible.

If you are satisfied with allowing the browser to determine the display format, you can use the toDateString or toLocaleDateString functions of the Date object. You will get different results on different browsers.

Otherwise, consider using a library such as moment.js, so you can control the format to your liking. For example:

moment([2014,9,8]).format('dddd, MMMM Do, YYYY')   // "Wednesday, October 8, 2014"

本文标签: javascriptHow to format date without time using toLocaleTimeStringStack Overflow