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

时间:2016-07-10 22:01:57

标签: javascript regex date datetime time

我正在编写一个node.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 Date / Time对象。但我不知道我是怎么做到的。

1 个答案:

答案 0 :(得分:0)

您可能需要查看Moment.js

此外,正则表达式本身应该得到一个完整的教程,它们是他们自己的语言。具体来说,请查看捕获组,这些组允许您将匹配表达式的某些部分外推。

您可以对输入做出哪些假设?会不会在某处隐藏一系列yyyy(...)mm(...)dd?

您可以尝试类似

的内容
def my_sort(list, new_array = nil)

  return new_array if list.size <= 0
  if new_array == nil
    new_array = []
  end
  min = list.min
  new_array << min
  list.delete(min)

  my_sort(list, new_array)

end

puts my_sort([3, 1, 2, 20, 11, 14, 3, 6, 8, 5])

(Haven还没试过这个表达,可能需要一些调整。)