如何将字符串转换为JavaScript日期对象?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
如何将字符串转换为JavaScript日期对象?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
当前回答
只是新日期(st);
假设这是正确的格式。
其他回答
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
输出将是:
dt => Date {Fri Apr 26 2013}
这个答案是基于卡塞姆的答案,但它也适用于两位数的年份。我对卡塞姆的答案进行了编辑,但以防它没有被批准,我还将这个作为单独的答案提交。
function stringToDate(_date,_format,_delimiter) {
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var year = parseInt(dateItems[yearIndex]);
// adjust for 2 digit year
if (year < 100) { year += 2000; }
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(year,month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
转换为pt-BR格式:
var dateString = "13/10/2014";
var dataSplit = dateString.split('/');
var dateConverted;
if (dataSplit[2].split(" ").length > 1) {
var hora = dataSplit[2].split(" ")[1].split(':');
dataSplit[2] = dataSplit[2].split(" ")[0];
dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
} else {
dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
}
我希望能帮助到别人!!
作为这里所解释的内容的一个插件,您可以使用new Date()创建日期,并使用非常有用的toLocaleDateString()函数对其进行格式化
一个例子:
console.log(new Date('1970-01-01').toLocaleDateString('es-ES')) //——>输出'1/1/1970'
我写了一个可重用的函数,当我从服务器获取日期字符串时使用。 您可以传递所需的分隔符(/ -等),用于分隔日、月和年,以便使用split()方法。 您可以在这个工作示例中看到并测试它。
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div>
<span>day:
</span>
<span id='day'>
</span>
</div>
<div>
<span>month:
</span>
<span id='month'>
</span>
</div>
<div>
<span>year:
</span>
<span id='year'>
</span>
</div>
<br/>
<input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
<span>28/10/1980
</span>
<script>
function convert(delimiter,dateString)
{
var splitted = dateString.split('/');
// create a new date from the splitted string
var myDate = new Date(splitted[2],splitted[1],splitted[0]);
// now you can access the Date and use its methods
document.getElementById('day').innerHTML = myDate.getDate();
document.getElementById('month').innerHTML = myDate.getMonth();
document.getElementById('year').innerHTML = myDate.getFullYear();
}
</script>
</body>
</html>