从 JavaScript 中的不同字符串中提取不同格式的日期

Extracting dates in different formats from different strings in JavaScript

本文关键字:格式 日期 提取 字符串 JavaScript      更新时间:2023-09-26

我正在编写一个节点.JS应用程序来解析来自谷歌相册的谷歌外卖数据,以获取EXIF数据。

我不擅长正则表达式,并且尝试过诸如 regexr.com 之类的网站无济于事,因为有很多未知数。但我想知道是否有更有效的方法可以做到这一点?

假设我可以有各种潜在的字符串

"IMG_20150628_184721-ANIMATION" # There is a date + time within, but they are not in an ISO format, also non-regular characters "Screenshot_2015-06-27-22-51-00" # Has a date/time at the end, but also has useless string within it "2015-06-28" # Cleanly formatted date without time "2015-06-28 22:51:05" # Cleanly formatted date and time "2015-06-28 #1" # Date + Space and Extra characters that I don't want "2015-06-28 #3 " # Date + Space and extra characters that I don't want and a trailing space "2015-06-18-19" # Date + An extra number (happens to be the next day) "NoDateOrTimeInThisString" # No Date "IMG_1234" # No date

此列表并不详尽,日期之前+之后可能还有其他字符串。日期/时间也可能实际上不在字符串中

没有任何办法知道我最终会得到这些特定文件名中的哪一个,在我的知识范围内,我不知道如何从每个文件名中提取日期。

有没有人知道我如何在 JavaScript 中做到这一点?比如图书馆?如果可能的话,我希望能够将其放入JS日期/时间对象中。但我不知道我该怎么做。

你可能想看看Moment.js。

此外,正则表达式本身应该有一个完整的教程,它们是一种自己的语言。具体来说,请查看捕获组,它允许您对匹配表达式的某些部分进行外加处理。

您可以对输入做出哪些假设?总会有一连串的yyyy(...毫米(...DD藏在里面的某个地方?

你可以尝试类似的东西

.*([0-9]{4}).*([0-9]{2}).*([0-9]{2}).*

(尚未尝试该表达式,可能需要一些调整。