如何将美国日期格式转换为欧洲日期格式

4

从:2011年5月19日

到:2011-05-19

当发现类似于5/40/2011等不真实的日期时,我需要它引发一个错误。是否有任何良好的库可以做到这一点?


3
"European" 格式并不存在,因为涉及到许多不同的选区和文化。 - Brian Scott
那么这个“2011-05-19”日期格式的正式名称是什么? - rsk82
1
这被称为大端序。http://en.wikipedia.org/wiki/Date_format_by_country - Shamis Shukoor
相关内容请参考:https://dev59.com/ikvSa4cB1Zd3GeqPifXW#2258351 - Adriano
3个回答

7
也许这不是最好的解决方案,但你可以尝试简单的方法,例如:
var from="5/19/2011";
var temp = from.split("/");
var to = temp[2] + "-" + temp[0] + "-" + temp[1];

1

那么Datejs这个开源日期库怎么样?具体来说:

http://code.google.com/p/datejs/wiki/APIDocumentation#parseExact

Date.parseExact("10/15/2004", "M/d/yyyy");  // The Date of 15-Oct-2004
Date.parse("15-Oct-2004", "d-MMM-yyyy");    // The Date of 15-Oct-2004
Date.parse("2004.10.15", "yyyy.MM.dd");     // The Date of 15-Oct-2004
Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]); // The Date of 15-Oct-2004

返回值 {日期} 一个日期对象,如果字符串无法转换为日期,则返回 null。

或者

http://code.google.com/p/datejs/wiki/APIDocumentation#validateDay

Date.validateDay(15, 2007, 1);  // true, 15-Feb-2007
Date.validateDay(31, 2007, 10); // false, throws RangeError exception

返回值 {布尔值} 如果在范围内则为true,否则为false。


我可以请您给-1一些反馈吗?我意识到这是一个非常老的回答,如果有人有任何评论,请分享。 - Alex KeySmith

1
保持简单: [编辑] 好的,您还想要一个检查,因此添加了fn chkDat:
function zeroPad(n){
  return (parseInt(n,10)<10 ? '0' : '') + n;
}

var usdat = '5/19/2011'.split('/')
    ,eudat = [usdat[2],zeroPad(usdat[0]),zeroPad(usdat[1])];

alert(chkDat(usdat,eudat); //=> true
alert(eudat.join('-'));    //=> '2011-05-19'

function chkDat(orig,eu){
   var eu = new Date(eu.join('/'));
   return   eu.getMonth()+1 === parseInt(orig[0],10)
         && eu.getDate() === parseInt(orig[1],10)
         && eu.getFullYear() === parseInt(orig[2],10)
   ;
}

注意,你需要的日期格式被称为日历日期ISO 8601)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接