Converting String into date format in JS

前端 未结 3 909
一个人的身影
一个人的身影 2020-12-22 14:37

I need to covert the string which contains date and time looks like this

\"27-JAN-15 08.30.00.000000 AM\"

When I use new Date(\"27-JAN-15

相关标签:
3条回答
  • 2020-12-22 14:40

    Manual parsing is the way to go.

    "27-JAN-15 08.30.00.000000 AM"

    First split you string at the "spaces", giving you

    "27-JAN-15"

    "08.30.00.000000"

    "AM"

    Now you can take the date part and split at the -, giving you

    "27"

    "JAN"

    "15"

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

    So JAN will give you 0, you now have

    "27"

    "0"

    "15"

    The year part is now ambiguous, Date will take values from 0 to 99 and map to the years 1900 to 1999. So you will need to decide how you are going to deal with this based on your data.

    Now the last 2 strings, you have

    "08.30.00.000000"

    "AM"

    The "AM" or "PM" can be ignored as the time is in 24 hour format, so now split the time string at ., giving you

    "08"

    "30"

    "00"

    "000000"

    The Date constructor only handles and accuracy of milliseconds, so you could take the "000000" and slice the first 3 digits, giving you

    "000"

    Now take all the parts that you have 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 javascript local date object, without cross browser parse inconsistencies.

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

    If your date is UTC then you may want to use

    Date.UTC()

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

    0 讨论(0)
  • 2020-12-22 14:47
    var dateVal = "27-JAN-15 08.30.00.000000 AM";
    console.log(new Date(dateVal.split(".").join(":")));
    
    0 讨论(0)
  • 2020-12-22 15:04
    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;
    }
    
    0 讨论(0)
提交回复
热议问题