【问题标题】:Ruby - Changing the date part of a Time instanceRuby - 更改时间实例的日期部分
【发布时间】:2011-01-19 09:28:12
【问题描述】:

我有一个 Time 实例 curr_time,其值为 Time.now,另一个 String target_date 的值为“2010 年 4 月 17 日”。如何将变量 curr_time 中的日期部分更改为 target_date 的值?

>> 当前时间 => 2010 年 2 月 21 日星期日 23:37:27 +0530 >> 目标日期 => “2010 年 4 月 17 日”

我希望 curr_time 像这样改变:

>> 当前时间 => 2010 年 4 月 17 日星期六 23:37:27 +0530

如何做到这一点?

【问题讨论】:

标签: ruby datetime time


【解决方案1】:

如果您使用 activesupport(例如在rails 环境中,或通过

require 'active_support'
require 'active_support/core_ext/date_time'

)

更改时间对象的示例。

>> t = Time.now
=> Thu Apr 09 21:03:25 +1000 2009
>> t.change(:year => 2012)
Thu Apr 09 21:03:25 +1000 2012

【讨论】:

【解决方案2】:

试试这个:

Time.parse(target_date) + curr_time.sec + curr_time.min * 60 + curr_time.hour * 60 * 60
=> Sat Apr 17 19:30:34 +0200 2010

您将获得 DateTime,其中 Date 来自 target_date,Time 来自 curr_time。

【讨论】:

  • 刚刚编辑了我的答案(我第一次没有让你正确......)。
  • 也可以这样表述:Time.parse(Time.now.to_date.to_s) + time.sec.seconds + time.min.minutes + time.hour.hours
【解决方案3】:

时间对象是不可变的,因此您必须创建一个具有所需值的新时间对象。像这样:

require 'time'
target = Time.parse(target_date)
curr_time = Time.mktime(target.year, target.month, target.day, curr_time.hour, curr_time.min)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多