在 RubyMotion 中获取当前月底作为时间对象



我需要在 rubymotion 中获取当前日历月的末尾作为时间对象。

因此,对于 2012 年

10 月,鉴于当前时间,我需要 2012 年 10 月 31 日午夜作为Time的实例,无论当前日期如何。

我该怎么做?

编辑

我很欣赏这些答案,但我忽略了一件事 - 抱歉 - 是我正在使用RubyMotion并且Date和DateTime对象不可用。

基本上,您加载的任何内容都require在红宝石中,我无法访问。

由于您使用的是RubyMotion,因此您可以访问所有iOS SDK:

NSDate *curDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components
    comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components
    // set last of month
    [comps setMonth:[comps month]+1];
    [comps setDay:0];
    NSDate *tDateMonth = [calendar dateFromComponents:comps];
    NSLog(@"%@", tDateMonth);

在获取一个月的最后一天找到

RubyMotion的翻译:

    curDate = NSDate.date
    calendar = NSCalendar.currentCalendar
    # Get necessary date components
    comps = calendar.components(NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit, fromDate:curDate)
    # set last of month
    comps.month += 1
    comps.day = 0
    tDateMonth = calendar.dateFromComponents(comps)
    NSLog("%@", tDateMonth)
我认为

这应该可以解决问题。

require 'date'
(DateTime.now.next_month - DateTime.now.day).to_time

例:

ruby-1.9.3-p194 :001 > require 'date'
 => true 
ruby-1.9.3-p194 :02 > DateTime.now
 => #<DateTime: 2012-10-10T17:18:15-05:00 ((2456211j,80295s,284081000n),-18000s,2299161j)> 
ruby-1.9.3-p194 :03 > DateTime.now.next_month - DateTime.now.day
 => #<DateTime: 2012-10-31T17:18:16-05:00 ((2456232j,80296s,819683000n),-18000s,2299161j)> 
ruby-1.9.3-p194 :04 > (DateTime.now.next_month - DateTime.now.day).to_time
 => 2012-10-31 17:18:18 -0500 

Ruby on Rails 方法

Time.now.at_end_of_month

您可以递增"开始"日期时间,直到它滚动到下个月:

require 'date'
def last_day_of_month(date=DateTime.now)
  month = date.month
  date += 1 while month == (date + 1).month
  date.to_time
end
last_day_of_month # => 2012-10-31 16:17:21 -0600
nov_1_2010 = DateTime.parse('2010-11-01T01:01:01-0700')
last_day_of_month(nov_1_2010) # => 2010-11-30 01:01:01 -0700 

最新更新