1

I was looking for EDT time and got this in this format :

Wed Nov 01 2017 06:42:26 GMT+0530 (India Standard Time)

Although, I just want it like 6:42 AM to display !! I tried date time function 
but doesnt help !! 

Is it advisable to do this with any string function or will it give issue in future (I dont want any calculation on this )

CodeWithCoffee
  • 1,896
  • 2
  • 14
  • 36

3 Answers3

2

Use moment.js format to work with date in JS.

moment("Wed Nov 01 2017 06:42:26 GMT+0530").format("hh:mm a")
Indent
  • 4,675
  • 1
  • 19
  • 35
0

You can use

var date = "Wed Nov 01 2017 06:42:26 GMT+0530";
var formattedDate = new Date(date);

var hours = formattedDate.getHours();
var minutes = formattedDate.getMinutes();

hours = (hours > 12) ? (hours - 12) : hours;
var period = (hours > 12) ? 'PM' : 'AM';

var time = hours + ':' + minutes + ' ' + period;

or you can also use moment.js, here is the details on 'format' function.

var time = moment(date).format("hh:mm A");
  • For 00:30 this will return 00:30 AM instead of 12:30 AM. Consider: `hours = hours % 12 || 12`. – RobG Nov 01 '17 at 12:10
-1
var date = new Date(); 

var hour = date.getHours();
var minutes = date.getMinutes();

var time = hour + ':' + minutes;

This would work.

Note: momentjs is great library for time manipulation, it is not good idea to include such a big library for small functions like this.

pmaddi
  • 449
  • 5
  • 18
  • I agree with you but to get AM/PM format with vanilla JS is little more complex. – Indent Nov 01 '17 at 11:09
  • 1
    The question was to get time in hours format. `var format = hour > 12 ? 'PM' : 'AM';` will give AM/PM format. But moment.js is really good suggestion. – pmaddi Nov 01 '17 at 11:16