0

I need to format this value in milliseconds "1543325996" to date like this "18/01/1970, 11:42:05 PM". I've already got the right result using 'toLocaleTimeString' function, but this result has String type. I need exactly Date type.

function dateFormat(date) {
   var formDate = new Date(+date).toLocaleDateString("en-GB");
   var formTime = new Date(+date).toLocaleTimeString("en-US");
   var concatDate = (formDate + ", " + formTime); 
    // here I've got error 'Invalid Date'. I know that it's a wrong way, but don't know what to do.
   var newDate = new Date(concatDate);    
return newDate;

}

but this returns error "Invalid Date". Is there another way to convert String to Date?

WORK
  • 29
  • 5
  • `new Date(+date)` – phuzi Feb 21 '19 at 12:28
  • It is not certain that `new Date(concatDate)` will be correctly parsed since you are not using a format supported by ECMA-262. Even if you were, there are browsers in use that will not correctly parse some of the supported formats, and some are not necessarily correctly parsed across implementations. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Why do you wan to do `new Date(concatDate)` anyway? You already have `new Date(+date)`. – RobG Feb 21 '19 at 13:26

1 Answers1

1

...but this result has String type. I need exactly Date type.

Date objects don't have a format. Formatting is intrinsically a textual thing (e.g., string).

If you want Dates, then new Date(+date) is giving you that. There's nothing further required. Later, at some point, if you want to display that date in a textual form, use toLocaleDateString or Intl.DateTimeFormat or similar to format them in the way you want them formatted. But not until/unless you need to convert them to text (a string).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875