Convert String to date format in JS

I need to hide a string that contains the date and time, what it looks like

"27-JAN-15 08.30.00.000000 AM"

When I use new Date("27-JAN-15 08.30.00.000000 AM") , I get an error like Invalid Date .

Please, help.

thanks

-7
source share
3 answers
 var dateVal = "27-JAN-15 08.30.00.000000 AM"; console.log(new Date(dateVal.split(".").join(":"))); 
+2
source
 var myDate = function(dateString) { var dateString = dateString || "27-JAN-15 08.30.00.000000 AM" // An example var newDate = new Date(dateString.split(" ")[0]); var hours = dateString.split(" ")[2]==="AM" ? dateString.split(" ")[1].split(".")[0] : parseInt(dateString.split(" ")[1].split(".")[0], 10) + 12; newDate.setHours(hours); newDate.setMinutes(dateString.split(" ")[1].split(".")[1]); newDate.setSeconds(dateString.split(" ")[1].split(".")[2]); newDate.setMilliseconds(dateString.split(" ")[1].split(".")[3]); return newDate; } 
+1
source

Manual disassembly is the way to go.

"27-JAN-15 08.30.00.000000 AM"

split first, you enter a string in the spaces, providing you

"27-JAN-15"

"08.30.00.000000"

"AM"

Now you can take part of the date and split in - by providing you

"27"

"JAN"

"15"

Now you can convert the month using object as a lookup table to give you a numerical value.

So JAN will give you 0 , now you have

"27"

"0"

"15"

Part of the year is now ambiguous, Date will take values ​​from 0 to 99 and display them in 1900-1999. Therefore, you will need to decide how you are going to deal with this based on your data.

Now the last two lines, you have

"08.30.00.000000"

"AM"

"AM" or "PM" can be ignored as time is in a 24-hour format, so now split the time string into . by providing you

"08"

"30"

"00"

"000000"

The Date constructor only handles precision and milliseconds, so you can take "000000" and slice first 3 digits, giving you

"000"

Now take all the parts you manually parsed and use them with the Date constructor

new Date(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);

So,

new Date("15", "0", "27", "08", "30", "00", "000");

You will now have a local javascript Date object without cross parse browsers.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

If your date is UTC, you can use

Date.UTC()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

0
source

Source: https://habr.com/ru/post/947235/


All Articles