0

I want to change the month date and time format in JavaScript. Currently I have got the time like this

Fri Sep 30 2016 17:30:00 GMT+0530 (IST)

But I want to convert it like this

2016, 9, 30, 17, 30, 0

So can someone tell me how to convert this date time in the required format? Any help and suggestions will be really appreciable. Thanks.

NewUser
  • 12,713
  • 39
  • 142
  • 236
  • 2
    Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Leon Adler Dec 06 '15 at 07:55
  • I recommend you to use moment.js library. – Aminadav Glickshtein Dec 06 '15 at 08:02
  • @Amina - depending on what the OP actually needs to do it is very possible that using an entire time manipulation/processing library would be over kill. For accessing the month/year/day of a date object, `moment.js` is not needed. Plain old vanilla JS will suffice. – Lix Dec 06 '15 at 08:04
  • @Lix - You have written an excellent answer. The comments section is a place to learn and discover new things, that not must be a direct answer to the question. – Aminadav Glickshtein Dec 06 '15 at 08:15
  • @Amina - thanks. You are correct about the comment section. I still believe that including an entire library should be a calculated decision based on how you plan to use the library. It's true that moment.js is a great tool - but in this context - it's simply too much. It's not a direct answer - but it's good to learn that including an entire library into your project is not always the correct thing to do - you need to decide whether or not you really need the library - in this case - I believe it is not needed. – Lix Dec 06 '15 at 08:19

2 Answers2

1

The data object that you get from calling: new Date() has properties that contain the exact values that you need:

var dateObj = new Date();
dateObj.getFullYear(); // 2015
dateObj.getMonth() // 11 (zero based - so this is December)
dateObj.getDay() // 0 (zero based - so this is Sunday)
...

There is a bunch more info available in the relevant documentation:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date#Getter

Lix
  • 47,311
  • 12
  • 103
  • 131
1

Lix's answer is correct but if you are looking to convert an existing string to a Date object you have to call Date() with the string as its argument:

var dateObj = new Date(datestring);

And so on, as Lix described.

Public Trust
  • 90
  • 1
  • 8