将字符串转换为轨道上的日期时间红宝石 [英] Convert string to datetime ruby on rails

查看:49
本文介绍了将字符串转换为轨道上的日期时间红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是基本的,但我已经挣扎了几个小时,我似乎无法应用将字符串转换为日期时间的众多方法之一,因此我可以将其保存在数据库中格式 2018-03-16 00:12:17.555372.提前致谢

I know this is basic but I've been struggling for a few hours now and I can't seem to apply one of the many ways there are to convert a string to datetime so I can save it in the database in this format 2018-03-16 00:12:17.555372. Thanks ahead

这是控制台输出的字符串.

This is the string output in the console.

params[:event][:start_date]
"03/28/2018 1:46 AM"

根据一些线索,我想出了一些非常肮脏的东西,也许有人可以帮助重构我正在抑制 AM 或 PM,因为我不知道如何解析,我知道非常感谢任何帮助!

Following some leads I've come up with smething really dirty maybe someone can help refactor I'm supressing AM or PM because I don't know how to parse that I know it's awfull any help is appreciated!

  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 从特定格式解析日期.

You can use DateTime to parse the date from a specific format.

如果您要解析的格式是03/28/2018 1:46 AM"那么你可以这样做.

if the format you are looking to parse is "03/28/2018 1:46 AM" then you can do this.

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)

您可以在这里参考所有格式.

这篇关于将字符串转换为轨道上的日期时间红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆