Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from string with milliseconds to date object Javascript

I got this problem when dealing with date time conversion. I have timestamp data from postgreSQL database with format like this one

"2011-04-04 19:27:39.92034"

In order to display it in highcharts, I have to convert it to date or time object. Without milliseconds, I easily convert it with Date.js

But milliseconds can't be handled with that library. I tried also with Date.parse but always got NaN.

Any solution for this problem? Thank you

like image 709
deerawan Avatar asked Apr 04 '11 12:04

deerawan


People also ask

How do you convert milliseconds to Date objects?

Approach : First declare variable time and store the milliseconds of current date using new date() for current date and getTime() Method for return it in milliseconds since 1 January 1970. Convert time into date object and store it into new variable date. Convert the date object's contents into a string using date.

How do you convert a string to a Date in JavaScript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

Is JavaScript Date now in milliseconds?

Date. now() returns the number of milliseconds since January 1, 1970.

What is Date now () in JavaScript?

The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


2 Answers

JS built in Date class should be able to handle this, and getTime() can return milliseconds since start 1970 (UNIX time). Watch out for time zone issues though; the constructor may interpret the date/time as being local, but getTime()'s milliseconds since 1970 may be in UTC, baking in a conversion that is difficult to remove.

new Date("2011-04-04 19:27:39.92034").getTime()
1301941659920
like image 85
Jim Blackler Avatar answered Nov 15 '22 08:11

Jim Blackler


Many ways to Rome. The given code will return '(datestr=) 2011-4-4 19:27:39.92'. Is that what you look for?

var darr = '2011-04-04 19:27:39.92034'.split('.')
  , dat=new Date(darr[0])
  , datestr = '';
dat.setMilliseconds(Math.round(darr[1]/1000));
datestr = [ [dat.getFullYear(),dat.getMonth()+1,dat.getDate()].join('-')
            ,' ', 
            [dat.getHours(),dat.getMinutes(),dat.getSeconds()].join(':')
            ,'.',
            dat.getMilliseconds()
          ].join('');
like image 43
KooiInc Avatar answered Nov 15 '22 09:11

KooiInc