如何使用javascript中的regexp从字符串中提取日期值?

时间:2016-01-28 11:13:56

标签: javascript regex

我有一个这样的字符串:

var value = "/Date(1454187600000+0300)/" - 从此我需要一个类似1/30/2016的日期格式 - 为此我尝试这样:

var value = "/Date(1454187600000+0300)/" // i need to fetch from here.
var nd = new Date(1454187600000); //this is static.
var month = nd.getUTCMonth() + 1; //months from 1-12
var day = nd.getUTCDate();
var year = nd.getUTCFullYear();
newdate = month + "/" + day + "/" + year;
console.log( newdate ); //works fine

但我不知道如何使用regexp从value变量中获取数字。任何人帮助我?

3 个答案:

答案 0 :(得分:0)

您可以使用捕获组来提取您正在寻找的日期部分:

nd = new Date(value.match(/\/Date\((\d+)/)[1] * 1);
//=> Sat Jan 30 2016 16:00:00 GMT-0500 (EST)

此处/\/Date\((\d+)/)[1]会为您提供"1454187600000"* 1会将该文字转换为整数。

答案 1 :(得分:0)

如果你想提取那个数字然后你不需要正则表达式,你可以简单地拆分字符串“/ Date(1454187600000 + 0300)/” 示例:“/ Date(1454187600000+0300)/”.split('+')[0],split('(')[1]

答案 2 :(得分:0)

一对捕获组将为您提供数字(以及您可以转换为数字的字符串),但是在将其传递给var value = "/Date(1454187600000+0300)/"; // Get the parts var parts = /^\/Date\((\d+)([-+])(\d{2})(\d{2})\)\/$/.exec(value); // Get the time portion as a number (milliseconds since The Epoch) var time = +parts[1]; // Get the offset in milliseconds var offset = (+parts[3] * 3600 + +parts[4] * 60) * 1000; // Apply the offset if (parts[2] == "+") { // The timezone is `+` meaning it's *ahead* of UTC, so we // *subtract* the offset to get UTC time -= offset; } else { // The timezone is `-` meaning it's *behind* UTC, so we // *add* the offset to get UTC time += offset; } // Get the date var dt = new Date(time); document.body.innerHTML = dt.toISOString();之前,您需要调整数字以计算时区,这很容易还有更多的捕获。见评论:



/^\/Date\((\d+)([-+])(\d{2})(\d{2})\)\/$/




正则表达式^是:

  • \/ - 输入开始
  • / - 文字Date
  • Date - 文字\(
  • ( - 文字(\d+)
  • ([-+]) - 一个或多个数字的捕获组;这是大数字
  • - - 偏移标志的捕获组+(\d{2})
  • (\d{2}) - 正好两位数的捕获组;这是偏移的小时部分
  • \) - 另外两位数的捕获组;这是偏移的分钟部分
  • ) - 文字\/
  • / - 文字$
  • int - 输入结束

Explanation on regex101