-5

I have a date string like '2019-06-12 12:02:12 232',how to convert to date using Javascript?

Date date = Date.parse('2019-06-12 12:02:12 232').format('yyyy-MM-dd dd:HH:ss SSS');

I want to compare two date to calculate the minisecond in Javascript.Any suggestion?How could I tweak my date string?The date string was generate is server side using Java:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);

This question does not contain minisecond,if no minisecond,Date.parse could solved the problem.My question is precise contain more detail operation of Javascript Date.

Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • `LocalDateTime` is exactly the *wrong* class to be using in Java for that purpose. I cannot think of any situation where calling `LocalDateTime.now()` is the right thing to do. That class cannot represent a moment as it purposely *lacks any concept of time zone* or offset-from-UTC. This is explained in the class Javadoc. Instead, to capture the current moment, use `Instant` for UTC, use `OffsetDateTime` for some other offset, or use `ZonedDateTime` for a particular time zone. – Basil Bourque Jun 19 '19 at 17:28

1 Answers1

3

You can do it like that:

let date_string = "2019-06-12 12:02:12 232"
let [y,M,d,h,m,s] = date_string.split(/[- :]/);
let yourDate =  new Date(y,parseInt(M)-1,d,h,parseInt(m),s);
console.log(`yourDate ${yourDate}`);

In addition, avoid using Date.parse() method.

UPDATE:

By using the above approach, you will avoid some strange bugs as described in the above link. However, it is possible to use a great library Moment.js:

moment("12-25-1995", "MM-DD-YYYY");

In addition, you could check if a date is valid:

moment("whether this date is valid").isValid(); // OUTPUT: false
StepUp
  • 36,391
  • 15
  • 88
  • 148