简体   繁体   English

使用JavaScript替换字符串中的日期

[英]Use JavaScript to replace a date inside of a string

I am struggling with javaScript replace and dates. 我正在努力用javaScript替换和日期。

In short, I have a string that has a date inside of it. 简而言之,我有一个带有日期的字符串。 I need to replace that date with a newly formatted date, while maintaining the string. 我需要在保留字符串的同时用新格式化的日期替换该日期。

var d1 = 'We met on 2014-02-20';
var d2 = 'I saw you again on Thursday, June 05, 2012';
var d3 = 'We had a great day on 2/15/2013';
var d4 = 'On March 07, 2015 we had to go to school';
var d5 = 'The vacation is between 1/1/15 and 1/2/15';

What I need is to get a standard date in all of these lines, but every solution just extracts the date and prints it. 我需要的是在所有这些行中获取标准日期,但是每种解决方案都只提取日期并将其打印出来。 The best article I have found involves JQUERY UI [ var dt1 = $.datepicker.formatDate('D, d M yy', new Date(d1)); 我发现的最佳文章涉及JQUERY UI [ var dt1 = $.datepicker.formatDate('D, d M yy', new Date(d1)); ], which works great, but it strips the date out of the string and I am left with the date only. ],效果很好,但它从字符串中去除了日期,只剩下日期了。

What I am trying to achieve is something like this: 我想要实现的是这样的:

var d1 = 'We met on 2014-02-20';
var d2 = 'I saw you again on Thursday, June 05, 2012';
var d3 = 'We had a great day on 2/15/2013';
var d4 = 'On March 07, 2015 we had to go to school';

TO

print_date_str(d1);

We met on Mon, 20 Feb 2014 我们在2014年2月20日星期一见面

print_date_str(d2);

I saw you again on Thu, 05 Jun 2012 我在2012年6月5日星期四再次见到您

print_date_str(d3);

We had a great day on Sun, 15 Feb 2013 我们度过了愉快的一天,2013年2月15日

print_date_str(d4);

On Fri, 07 Mar 2015 we had to go to school 2015年3月7日星期五,我们不得不上学

print_date_str(d5);

'The vacation is between Tue, 01 Jan 2015 and Wed, 02 Jan 2015 ' 假期在2015年1月1日星期二至2015年1月2日 星期三之间

Here is a JSFIDDLE showing Jquery UI date format: http://jsfiddle.net/k7qrw8o7/1/ 这是一个显示Jquery UI日期格式的JSFIDDLE: http : //jsfiddle.net/k7qrw8o7/1/

Your guidance and help is greatly appreciated. 非常感谢您的指导和帮助。

Here is a good site to reference for formatting JavaScript dates. 这是一个用于格式化JavaScript日期的好站点。 MS JS time var date = new Date(Date.UTC(2014, 1, 20)); MS JS time var date = new Date(Date.UTC(2014, 1, 20)); then you would do var d1Date = date.toLocaleDateString("en-US") then var d1 = 'We met on '+ d1Date; 那么您将执行var d1Date = date.toLocaleDateString("en-US")然后var d1 = 'We met on '+ d1Date;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM