有没有办法改变日期格式:
30. Jan 2008
28. Dec 2010
到此(isodate):
2008-01-30
2010-12-28
使用正则表达式?我工作的语言是JS。
感谢。
答案 0 :(得分:0)
您不需要任何正则表达式。如果输入dateString的模式是固定的。然后就可以这样做:
<button onclick="myFunction()">Date convert</button>
<p id="demo"></p>
<script>
function myFunction() {
var dateString = "30. Jan 2008";
var day = dateString.substring(0,2);
var month = dateString.substring(4,7);
var year = dateString.substring(8, dateString.length);
var monthNameToNumberObj = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"};
document.getElementById("demo").innerHTML = year+"-"+monthNameToNumberObj[month]+"-"+day;
}
</script>
[请注意我假设年份将始终为4位数,日期将为2位数。如果他们担心,那么你需要使用拆分功能来提取日,月和年]
答案 1 :(得分:0)
将您的日期解析为可传递给new Date
的部分通常总是更好,这样您就可以获得可以使用的日期对象
像
这样的东西
var date = "30. Jan 2008";
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var parts = date.split(' ').map(x=>x.replace('.',''));
var dObj = new Date(parts[2], months.indexOf(parts[1]), parts[0]);
var zero = (x) => x < 9 ? '0' + x : x;
var parsed = dObj.getFullYear() + '-' + zero(dObj.getMonth()+1) + '-' + dObj.getDate();
console.log(parsed)
&#13;