8

Javascript method

var d = new Date();

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

8 Answers8

11

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();
Waqas Ghouri
  • 1,079
  • 2
  • 16
  • 36
8

I would advise you to use dayjs or 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);

Or in a simplified way:

var d = new Date();
d.setHours(0, 0, 0, 0);

Or as a one line function:

function now () { const d = new Date(); d.setHours(0, 0, 0, 0); return d }

now(); // returns the current date

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

Micaël Félix
  • 2,697
  • 5
  • 34
  • 46
4

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.

Pogrindis
  • 7,755
  • 5
  • 31
  • 44
4

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"
CSquared
  • 155
  • 3
  • 11
4

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

var date = new Date().toISOString().slice(0,10);
RRR
  • 507
  • 4
  • 17
1

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);
fboes
  • 2,149
  • 16
  • 17
1

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.

Dima Dorogonov
  • 2,297
  • 1
  • 20
  • 23
0
const dateWithoutTime = new Date(Math.floor(date.getTime() / 86400000) * 86400000)