这应该是如此简单,但我错过了一些东西。
当尝试将字符串转换为日期时,我得到一个无效的日期。
irb(main):076:0> current_date
=> "December 21, 2022 04.00 AM"
irb(main):077:0> current_date.class
=> String
irb(main):078:0> date_format
=> "%M %e, %Y"
irb(main):079:0> date_format_time
=> "%M %e, %Y %l.%i %p"
irb(main):080:0> new_date = Date.strptime(current_date, date_format).iso8601
Traceback (most recent call last):
2: from (irb):80
1: from (irb):80:in `strptime'
Date::Error (invalid date)
irb(main):081:0> new_date = Date.strptime(current_date, date_format_time).iso8601
Traceback (most recent call last):
3: from (irb):80
2: from (irb):81:in `rescue in irb_binding'
1: from (irb):81:in `strptime'
Date::Error (invalid date)
我正在尝试将日期转换为格式为'YYYY-MM-DD'的字符串
提前感谢!
您的date_format_time
感觉不对。试试这个:
current_date = "December 21, 2022 04.00 AM"
date_format_time = "%B %e, %Y %I.%M %p"
Date.strptime(current_date, date_format_time).iso8601
#=> "2022-12-21"
顺便说一句。我建议http://strftime.net/玩和分析strptime的格式代码。