Javascript date method without time

限于喜欢 提交于 2020-07-21 05:05:35

问题


Javascript method

var d = new Date();

get datetime value, but how get clear date, without time ?


回答1:


There are so many examples of this..

function format(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

var today = new Date();
var dateString = format(today);
alert(dateString);

I also like to point out whenever dealing with time.. MomentJS really is the perfect tool for the job

MomentJS

another super simple example...

var today = new Date();
alert(today.toLocaleDateString());

second example is my favourite.




回答2:


For complete reference of parsing date Follow link here

You can simply parse only date from you variable like

d.toJSON().substring(0,10)

or

d.toDateString();



回答3:


I would advise you to use momentjs (http://momentjs.com/) for all your javascript problems concerning dates.

This code will reset hours, minutes, seconds, milliseconds of your javascript date object.

var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);

Without conversion, and you still have a date object at the end.




回答4:


With Date you have a date object, which has several methods. A complete list of methods can be found in the Javascript Date object documentation.

In your case:

var d = new Date(),
    datestring = '';

datestring = d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate()

alert(datestring);



回答5:


Depending on what format you like, I think these are the easiest ways to get just the date without the time.

new Date().toJSON().split("T")[0];
// Output: "2019-10-04"

or

new Date().toLocaleDateString().split(",")[0]
// Output in the US: "10/4/2019"



回答6:


new Intl.DateTimeFormat('en-GB').format(new Date('2018-08-17T21:00:00.000Z'))

The result will be: 18/08/2018

You can check the description here.




回答7:


I always use this method, it will return only current date:

var date = new Date().toISOString().slice(0,10);


来源:https://stackoverflow.com/questions/26528085/javascript-date-method-without-time

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