Date.parse(2/4/2011 9:34:48 AM)

后端 未结 3 588
北荒
北荒 2021-01-24 05:30

my input will be from a variable (Ticket.CreationDate) and will look like

2/4/2011 9:34:48 AM (it will vary of course)

Ideally I could pass in the variable as-i

3条回答
  •  暖寄归人
    2021-01-24 06:23

    The fact that you have a static format makes a solution simple.

    var dateReg = 
        /(\d{1,2})\/(\d{1,2})\/(\d{4})\s*(\d{1,2}):(\d{2}):(\d{2})\s*(AM|PM)/;
    function parseDate(input) {
        var year, month, day, hour, minute, second,
            result = dateReg.exec(input);
        if (result) {
            year = +result[3];
            month = +result[1]-1; //added -1 to correct for the zero-based months
            day = +result[2];
            hour = +result[4];
            minute = +result[5];
            second = +result[6];
            if (result[7] === 'PM' && hour !== 12) {
                hour += 12;
            }       
        }
        return new Date(year, month, day, hour, minute, second);
    }
    

提交回复
热议问题