简体   繁体   English

将dd.mm.yyyy格式转换为yyyy-mm-dd

[英]Convert dd.mm.yyyy format to yyyy-mm-dd

How can I convert dd.mm.yyyy format date to yyyy-mm-dd format in JavaScript? 如何在JavaScript中将dd.mm.yyyy格式日期转换为yyyy-mm-dd格式?

Here is an example: 这是一个例子:

30.01.2010
to 
2010-01-30

Meaning convert dmY to Ymd. 意思是将dmY转换为Ymd。 I know how to do this in PHP but I need it in JavaScript. 我知道如何在PHP中执行此操作,但我需要在JavaScript中使用它。

You can do this pretty simply. 你可以很简单地做到这一点。 Just split the european date into an array, reverse it, and then join it with dashes. 只需将欧洲日期分成一个数组,然后将其反转,然后用破折号加入它。

var euro_date = '30.01.2010';
euro_date = euro_date.split('.');
var us_date = euro_date.reverse().join('-');

Datejs can parse that. Datejs可以解析它。 The code is at http://datejs.googlecode.com/files/date.js 代码位于http://datejs.googlecode.com/files/date.js

EDIT: It is not safe to left date.js determine the format string automatically. 编辑:这是不安全的左date.js自动确定格式字符串。 I made the mistake of not testing with a day <= 12 (duh). 我错了一天<= 12(duh)没有测试。 You should use: 你应该使用:

Date.parseExact('09.01.2010', 'd.M.yyyy').toString('yyyy-MM-dd');

or 要么

Date.parseExact('09.01.2010', 'dd.MM.yyyy').toString('yyyy-MM-dd');

depending on whether you want to allow single digit days. 取决于您是否要允许单位数天。

Datejs is a bit bloated if you only need to do this. 如果你只需要这样做,Datejs有点臃肿。 You can use split() and concatenate the results: 您可以使用split()并连接结果:

var eu_date = '30.01.2010';
var parts = eu_date.split('.');
var us_date = parts[2]+'-'+parts[1]+'-'+parts[0];

For these kinds of conversions where no date logic is needed, it's usually smartest to just use string manipulation tools. 对于不需要日期逻辑的这类转换,通常最聪明的就是使用字符串操作工具。

    function stringToDate( value ) {
      var isEuro = value.match( /^\d{1,2}\.\d{1,2}\.\d{4}$/ )
      var isIso = value.match( /^\d{4}-\d{1,2}-\d{1,2}$/ )

      if ( isEuro ) {
        value = value.split('.')
        value = [value[2],value[1],value[0]].join('-') //.reverse() isn't working in IEdge
        isIso = true
      }

      if ( isEuro || isIso ) {
        var date = new Date( value )
      }

      if ( isNaN( date.getTime() ) || !isIso ) {
         return false
      }


      return date
    }

    stringToDate('30.01.2000') //Sun Jan 30 2000 00:00:00 GMT+0100 (CET)
    stringToDate('30.1.2000') //Sun Jan 30 2000 01:00:00 GMT+0100 (CET)
    stringToDate('2000-01-30') //Sun Jan 30 2000 01:00:00 GMT+0100 (CET)
    stringToDate('2000-1-30') //Sun Jan 30 2000 01:00:00 GMT+0100 (CET)

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

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