3

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 common way where today's date can be converted to any given format

  • `console.log(new Intl.DateTimeFormat('en-US').format(new Date()));` – Aniket Sahrawat Feb 23 '18 at 06:58
  • 1
    Caution with Intl, it's not supported by all browsers (see browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl). You can use moment.js (https://momentjs.com/) – Marc Feb 23 '18 at 07:04
  • Your comment 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 Feb 23 '18 at 07:04
  • I am looking for a common way where todays date can be converted to any given format –  Feb 23 '18 at 07:04
  • 1
    @Marc, thanks for that link. I'm comparing it to https://caniuse.com/#search=intl which presents it in a more favorable light. Looking at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/format appears to show a more specific view related to the format portion of DateTimeFormat. – Jason Aller Feb 23 '18 at 07:07

2 Answers2

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

RoboBear
  • 5,434
  • 2
  • 33
  • 40
3

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); 
MathanKumar
  • 102
  • 1
  • 1
  • 11
  • This will work but I dont want a particular format. It should get changed to any given format like yyyy.mm.dd or dd-mm-yyy. I dont want to write code for everything. Is there any way to do this. –  Feb 23 '18 at 07:01
  • I think jquery might not support this by default. https://stackoverflow.com/a/11261274 in this question they used a plug-in to do this. – AK_is_curious Feb 23 '18 at 07:08