从字符串中提取日期

从字符串中提取日期

本文介绍了Javascript:从字符串中提取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式化为任一格式的字符串

I have a string formatted as either

Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM

我需要做的是以某种方式将字符串的日期部分提取到一个变量中,即.今天"、昨天"或格式为 DD/MM/YYYY 的日期.

What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.

这样的事情可以用 Javascript 实现吗?

Is something like this possible at all with Javascript?

推荐答案

由于 JavaScript 日期解析器无法识别您的日期,您可以编写一个解析器,将日期放入它可以识别的格式.这是一个函数,它采用您提供的日期示例并将其格式化以获取有效的日期字符串:

Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:

function strToDate(dateStr) {
    var dayTimeSplit = dateStr.split(" ");
    var day = dayTimeSplit[0];
    var time = dayTimeSplit[1];

    if (day == "Today") {
        day = new Date();
    } else if (day == "Yesterday") {
        day = new Date();
        day.setDate(day.getDate() - 1);
    } else {
        day = new Date(day);
    }

    var hourMinutes = time.substring(0, time.length -2);
    var amPM = time.substring(time.length -2, time.length);

    return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
        + " " + hourMinutes  + " " + amPM);
}

然后您可以调用 stroToDate 将您的日期格式转换为有效的 JavaScript 日期:

Then you can call stroToDate to convert your date formats to a valid JavaScript Date:

console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));

输出:

Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)

这篇关于Javascript:从字符串中提取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:14