最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to determine date format from string? - Stack Overflow

programmeradmin1浏览0评论

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.

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?

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

This question can be divided in 2 answer.

  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)

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

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.

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?

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

This question can be divided in 2 answer.

  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)

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

Share Improve this question asked Dec 29, 2016 at 14:12 Kaushik ThankiKaushik Thanki 3,5203 gold badges28 silver badges55 bronze badges 6
  • A simple solution could be: use a date/time library such as moment.js – dloeda Commented Dec 29, 2016 at 14:41
  • 2 You cannot, not at least reliably. Is 1/2/2016 Jan 2nd or Feb 1st? – Álvaro González Commented Dec 29, 2016 at 15:06
  • seems u guys have not understand the need properly,, – Kaushik Thanki Commented Dec 29, 2016 at 15:28
  • Could you check if all possible formats are those under ISO 8601? If they are the code may simplify greatly. If they are not, if you could specify it in the main post the answers will be more precise. – Desaroll Commented Dec 29, 2016 at 17:18
  • @KaushikThanki You can edit the question and add some clarifications. It's not as if we were intentionally misunderstanding the question. (Because if all you want is parse a string with a known format then you have like a hundred duplicates to copy code from.) – Álvaro González Commented Dec 30, 2016 at 8:18
 |  Show 1 more comment

4 Answers 4

Reset to default 7

Tl;Dr

You can't do this it's impossible.


There's a lot of snake oil getting sold here.

Date formats are not mutually exclusive, two (or more) formats may look the same but the values represent different parts of a date. This makes it practically impossible to determine the date format from a string.

For example, 01/02/2022 is 1st Feb 2022 in UK format and 2nd Jan 2022 in US format. So given the string 01/02/2022 you cannot determine whether this is uk or us format.

Given an imaginary method returnFormat("01/02/2022") what would you expect the response to be here? It might return en-US or en-GB or an of the other overlapping formats.

Date formats were not designed with computer parsing in mind. The only date format designed for computers is a ISO 8601 format (e.g. 2008-05-11T15:30:00Z) which can include the UTC offset. so times with a Z are utc and +01:00 would be UTC +1. This format is specifically chosen so as not to clash with any human readable formats for the problems outlined above.

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
}

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

@Liam's answer is pragmatically correct. My 2 cents:

const unixDatetime = Date.parse("2018-01-01T20:09:00");
const datetime = luxon.DateTime.fromMillis(unixDatetime);
const presentableDatetime = datetime.toFormat("fff");

It gets the work done. It will parse the date in milliseconds from "January 1, 1970, 00:00:00 UTC" (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). Then convert milliseconds to a DateTime object with Luxon and parse them to the format you select (https://moment.github.io/luxon/#/formatting?id=table-of-tokens).

Date.parse() can parse various formats, which is neat. But, be careful. If you clicked on the Date.parse() documentation you must have read that

Only the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.

Try running the following and observe the results:

var unix_datetime = Date.parse("20:09:00 1-12-2018");
// 1515780540000 (which is January 12, 2018 6:09:00 PM)

var unix_datetime_browsers = Date.parse("2018 12 01 20:09:13Z");
// 1543687753000 (in Chrome which is December 1, 2018 6:09:13 PM)
// NaN (in Firefox)

@Liam said it, the structure of the datetime string is unclear and inherently "unparsable" without knowing the format. Is January 12 correct, or should it be December 1? Also timezones!! Also, cross-browser compatibility (MDN website explicitly discourages using it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).

Despite the above, Date.parse() is pretty helpful. Trust its results only when using ISO 8601 strings. Though, if it is ISO 8601, then you could just do:

var datetime = luxon.DateTime.fromISO("2018-01-01T20:09:00");
var presentableDatetime = (datetime.isValid) ? datetime.toFormat("fff") : "";

think about that

05/06/1990

You can't determine which digits are for month info and which are for day info. So you can't do it automatically.

发布评论

评论列表(0)

  1. 暂无评论