我知道这是基本的,但我现在已经苦苦挣扎了几个小时,我似乎无法应用将字符串转换为日期时间的众多方法之一,所以我可以将它保存在数据库中,格式为2018- 03-16 00:12:17.555372.谢谢你
这是控制台中的字符串输出.
params[:event][:start_date] "03/28/2018 1:46 AM"
[编辑]跟随一些线索,我想出了一些非常脏的东西也许有人可以帮助重构我正在压抑上午或下午,因为我不知道如何解析我知道它很糟糕任何帮助表示赞赏!
if !params[:event][:start_date].empty? start_date = params[:event][:start_date] start_date = start_date.gsub(/[AMP]/, '').squish a = start_date.split('/') tmp = a[0] a[0] = a[1] a[1] = tmp a = a.split(',').join('/') start_date = Time.parse(a) end if !params[:event][:end_date].empty? end_date = params[:event][:end_date] end_date = end_date.gsub(/[AMP]/, '').squish a = end_date.split('/') tmp = a[0] a[0] = a[1] a[1] = tmp a = a.split(',').join('/') end_date = Time.parse(a) end您可以使用 DateTime从特定格式解析日期.
如果您要解析的格式是“03/28/2018 1:46 AM”,那么您可以这样做.
date = DateTime.strptime('03/28/2018 1:46 AM', '%m/%d/%Y %I:%M %p') # date to ISO 8601 puts date.to_time # output: 2018-03-28 07:16:00 +0530 puts date.strftime("%m/%d/%Y") # output: 03/28/2018
日期格式:
Date (Year, Month, Day): %Y - Year with century (can be negative, 4 digits at least) -0001, 0000, 1995, 2009, 14292, etc. %m - Month of the year, zero-padded (01..12) %_m blank-padded ( 1..12) %-m no-padded (1..12) %d - Day of the month, zero-padded (01..31) %-d no-padded (1..31) Time (Hour, Minute, Second, Subsecond): %H - Hour of the day, 24-hour clock, zero-padded (00..23) %k - Hour of the day, 24-hour clock, blank-padded ( 0..23) %I - Hour of the day, 12-hour clock, zero-padded (01..12) %l - Hour of the day, 12-hour clock, blank-padded ( 1..12) %P - Meridian indicator, lowercase (``am'' or ``pm'') %p - Meridian indicator, uppercase (``AM'' or ``PM'') %M - Minute of the hour (00..59)
您可以参考所有格式here.