添加自定义时间到日期

huangapple go评论50阅读模式
英文:

Adding custom time to date

问题

时间戳的格式无法直接添加到 Ruby 日期中。我该如何做?

sd = Date.parse('2016-01-01')
z = "4:00am"

如何将 z 添加到 sd 中?

英文:

the timestamp is in a format that I am not able to add to the ruby date. How can I do this?

 sd=Date.parse('2016-01-01')
 z="4:00am"

How do I add z into sd?

答案1

得分: 2

你不能直接将时间添加到日期,但可以像这样解析时间(只需连接日期和时间)

date = '2016-01-01'
time = '4:00am'
require 'time'

Time.parse("#{date} #{time}")
# => 2016-01-01 04:00:00 +0300

为了避免一些解析错误,你可以明确指定指令

DateTime.strptime("#{date} #{time}", '%Y-%m-%d %H:%M%p')
英文:

You can't add time to date but you can parse time like this (just concatenate date and time)

date = '2016-01-01'
time = '4:00am'
require 'time'

Time.parse("#{date} #{time}")
# => 2016-01-01 04:00:00 +0300

To avoid some parsing misinterpretation you can explicitly point directives

DateTime.strptime("#{date} #{time}", '%Y-%m-%d %H:%M%p')

huangapple
  • 本文由 发表于 2023年1月9日 05:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定