如何从字符串确定日期格式? [英] How to determine date format from string?

查看:110
本文介绍了如何从字符串确定日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经在今天提出,但是所有者似乎已将其删除(即使它有4票赞成)。但是,这个问题是如此有趣,我决定自行发表。

This question was already asked today but the owner seems have deleted it(even it has 4 up vote). However the question was so interesting, I have decided to post by my self again.

我在Javascript中有一个对象,该对象具有一个带有日期字符串的属性。

I have an object in Javascript which has one property with a date string.

现在我要设置一个新日期时间添加到该属性,但是如何在不知道其格式的情况下设置新数据?

Now I want set a new datetime to that property, but how can I set the new data without knowing its format?

示例日期时间如下所示: 2018-01-01T20: 09:00

The sample datetime looks like this "2018-01-01T20:09:00"

该问题可以分为2个答案。

This question can be divided in 2 answer.


  1. 标识当前提到的格式&为对象属性设置相同的格式。(如果有人说这是什么类型的日期时间格式,这似乎很容易实现)

  1. Identify the current mentioned format & set the the same format to object property.(This seems to be achieved easily if someone say what type of datetime format is this)

标识一些通用解决方案确定任何日期时间格式&将给定的datetime转换为set object属性。

Identify some generic solution that determine any datetime format & convert given datetime to set object property.


推荐答案

如果可以使用moment.js,则可以执行以下操作:

If you can use moment.js then the following does the job:

var dateFormats = {
  "iso_int" : "YYYY-MM-DD",
  "short_date" : "DD/MM/YYYY",
  "iso_date_time": "YYYY-MM-DDTHH:MM:SS",
  "iso_date_time_utc": "YYYY-MM-DDTHH:MM:SSZ"
   //define other well known formats if you want
}

function getFormat(d){
  for (var prop in dateFormats) {
        if(moment(d, dateFormats[prop],true).isValid()){
           return dateFormats[prop];
        }
  }
  return null;
}

var dateInput = "2018-01-01T20:09:00";

var formatFound = getFormat(dateInput); //returns "YYYY-MM-DDTHH:MM:SS"
if(formatFound !==null){
   //do stuff
}

检查默认情况下,请查看js文档以获取有关默认支持的dateFormats的更多信息,并使用它们填充您的dateFormats对象。

Check the moment js docs for more info on the supported dateFormats by default and populate your dateFormats object with them.

这篇关于如何从字符串确定日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆