admin管理员组

文章数量:1304152

I am trying to convert today's date in particular format and this date format can be anything like - dd/mm/yyyy or yyyy.mm.dd and so on

var date = new Date();
var todaysDate = date.toString('mm/dd/yyyy');

However, this code is not working. Is there any other way to get it done.

I am looking for a mon way where today's date can be converted to any given format

I am trying to convert today's date in particular format and this date format can be anything like - dd/mm/yyyy or yyyy.mm.dd and so on

var date = new Date();
var todaysDate = date.toString('mm/dd/yyyy');

However, this code is not working. Is there any other way to get it done.

I am looking for a mon way where today's date can be converted to any given format

Share Improve this question edited Feb 23, 2018 at 7:05 asked Feb 23, 2018 at 6:46 user8530455user8530455 5
  • console.log(new Intl.DateTimeFormat('en-US').format(new Date())); – Aniket Sahrawat Commented Feb 23, 2018 at 6:58
  • 1 Caution with Intl, it's not supported by all browsers (see browser patibility - developer.mozilla/en-US/docs/Web/JavaScript/Reference/…). You can use moment.js (momentjs.) – Marc Commented Feb 23, 2018 at 7:04
  • Your ment that "I dont want a particular format. It should get changed to any given format like yyyy.mm.dd or dd-mm-yyy." should be made clear in the question. – Jason Aller Commented Feb 23, 2018 at 7:04
  • I am looking for a mon way where todays date can be converted to any given format – user8530455 Commented Feb 23, 2018 at 7:04
  • 1 @Marc, thanks for that link. I'm paring it to caniuse./#search=intl which presents it in a more favorable light. Looking at developer.mozilla/en-US/docs/Web/JavaScript/Reference/… appears to show a more specific view related to the format portion of DateTimeFormat. – Jason Aller Commented Feb 23, 2018 at 7:07
Add a ment  | 

2 Answers 2

Reset to default 5

You could use Moment JS -- my go to JS date library -- to do something like

Moment (new Date ()).format("MM/DD/YYYY")

Or, if you know the form of the datetime format of the input string

Moment(string, "DD/MM/yyyy").format("MM/DD/YYYY")

MomentJS has other advantages too like adding time or dates or diffing two datetimes.

Alternatively, you could use Date Class functions to get parts of a Datetime and custom print or format them.

See StackOverflow format JS Date

I think, it is useful for u.

  var currentDt = new Date();
    var mm = currentDt.getMonth() + 1;
    var dd = currentDt.getDate();
    var yyyy = currentDt.getFullYear();
    var date = mm + '/' + dd + '/' + yyyy;
    alert(date); 

本文标签: javascriptConvert today39s date to given formatStack Overflow