0

我有字符串格式的日期,有时是这样的:05-11-2009 16:59:20有时是这样的:2013-12-05T22:00:00:00Z而其他一些时间是这样的:2013-12-05T22:00:00:00.000Z

我编写了一个从这些日期中提取月日和年的函数,但我想要一个可以为所有输入格式的函数工作的函数。就像是:

function DateParts(datetime, format) {
    var matches = datetime.splitByFormat(format);

    this.getYear = function () {
       return matches[3];
    };
    this.getMonth = function () {
        return (matches[2] - 1) +"" ;
    };
    this.getDay = function () {
        return matches[1];
    };
    this.getHours = function () {
        return matches[4];
    };
    this.getMinutes = function () {
    return matches[5];
    };
    this.getSeconds = function () {
        return matches[6];
    };
};

格式将是什么"yyyy-mm-dd hh:MM:ss""dd-mm-yyyyThh:MM:ss.dddZ"什么。

有没有一种很好的方法来创建 splitByFormat 函数而不必把我的头弄掉?

4

3 回答 3

2

一个正则表达式可以找到它们:

(((?<month>\d{2})-(?<day>\d{2})-(?<year>\d{4})\s(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}))|((?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}):(?<millisecond>\d{2})Z)|(?<year>(\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}):(?<millisecond>\d{2})\.(?<centisecond>\d{3})Z))

如果您使用此正则表达式字符串,您可以捕获不同的分组:

  • 小时
  • 分钟
  • 第二
  • 毫秒
  • 厘秒
于 2013-07-11T13:42:07.267 回答
1

这个简单的课程FormatAnalyzer可能是一个开始。有用。

FormatAnalyzer f = new FormatAnalyzer("yyyy-mm-dd hh:MM:ss");
f.getYear("2013-07-11 15:39:00");
f.getMonth("2013-07-11 15:39:00");

在哪里

public class FormatAnalyzer {

    private String format;
    private int yearBegin;
    private int yearEnd;
    private int monthBegin;
    private int monthEnd;
    // ...

    public FormatAnalyzer(String format) {
        this.format = format;
        analyzeFormat();
    }

    public String getYear(String date) {
        return date.substring(yearBegin, yearEnd);
    }

    public String getMonth(String date) {
        return date.substring(monthBegin, monthEnd);
    }

    private void analyzeFormat() {
        yearBegin = yearEnd = format.indexOf("y");
        while (format.indexOf("y", ++yearEnd) != -1) {
        }
        monthBegin = monthEnd = format.indexOf("m");
        while (format.indexOf("m", ++monthEnd) != -1) {
        }
        // and so on for year, day, ...
    }
}
于 2013-07-11T13:47:17.213 回答
1

那这个呢?有更好的人吗?

function DateParts(datetime, format) {

    this.getYear = function () {
        if (format) {
            ind = format.indexOf("yyyy");
            return datetime.substring(ind, ind + 4);
        }
         return "";

    };
    this.getMonth = function () {
        if (format) {
            ind = format.indexOf("mm");
            return datetime.substring(ind, ind + 2);
        }
        return "";            
    };
    this.getDay = function () {
        if (format) {
            ind = format.indexOf("gg");
            return datetime.substring(ind, ind + 2);
       }
       return "";
    };
};
于 2013-07-11T13:39:18.540 回答