0

For example, I have this string "2020-09-09T21:00:14.114-04:00"

I grab this from my database and in its current form, it is a string. my goal is to have it display

4 PM instead of the long string of jibberish

is it possible to accomplish this?

I was thinking of possibly creating a new date object like

let test = new Date('2020-09-09T21:00:14.114-04:00').

but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible

edit: i would like the desired output to be the hour:minute and then am/pm

ex 10:15pm

vape
  • 53
  • 5
  • Please explain what is the desired output you are expecting for the date? – Vimal Patel Oct 25 '20 at 04:06
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) and [*How to format a JavaScript date*](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date). – RobG Oct 25 '20 at 04:14

2 Answers2

0

You can do that by parsing the date from your database using Date.parse(). Then you can get the time or whatever you need using date.toLocalTimeString() in your case.

let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();

console.log(time); // --> "4:00:14 AM"

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

Here's some useful resources MDN Date.parse() MDN Date.toLocalTimeString()

Wael Zoaiter
  • 549
  • 4
  • 7
0

You can do as following way.new Date() is used to get the current date and time.

var today = new Date();
var time = today.getHours(); 

if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}