Heroku console weird date issue
I have a cron task that runs once a day, using Heroku's Daily Cron addon. The cron takes values from yesterday's data and creates required objects with today's timestamp. But, I am facing unusual circumstances. This is from Heroku console :
>> Date.today
=> Thu, 25 Aug 2011
>> Date.yesterday
=> Thu, 25 Aug 2011
>> DateTime.now
=> Thu, 25 Aug 2011 23:31:42 -0700
The current time being 23:31, I thought of giving it a try later on. This is what I have now :
>> Date.today
=> Fri, 26 Aug 2011
>> Date.开发者_如何学运维yesterday
=> Thu, 25 Aug 2011
>> DateTime.now
=> Fri, 26 Aug 2011 00:35:14 -0700
Any ideas why Date.today and Date.yesterday provide the same result. Is it due to the timezone or other certain settings ?
Thanks
Date.today represents date according to your server time irrespective of the time zone that you have set.
Date.yesterday is Time.now.in_time_zone - 1.day. It depends on Time.zone that we have set
This example should clarify it:
ruby-1.9.2-p180 :014 > Time.now => 2011-08-26 03:21:10 +0545
ruby-1.9.2-p180 :015 > Time.zone => (GMT+00:00) UTC
ruby-1.9.2-p180 :016 > Time.now.in_time_zone => Thu, 25 Aug 2011 21:36:40 UTC +00:00
ruby-1.9.2-p180 :018 > Date.yesterday => Wed, 24 Aug 2011
ruby-1.9.2-p180 :017 > Date.today => Fri, 26 Aug 2011
Now,after setting time-zone as Kathmandu. Date.yesterday changes as expected but there is no change to Date.today
ruby-1.9.2-p180 :019 > Time.zone="Kathmandu" => "Kathmandu"
ruby-1.9.2-p180 :022 > Time.now.in_time_zone => Fri, 26 Aug 2011 03:55:28 NPT +05:45
ruby-1.9.2-p180 :020 > Date.yesterday=> Thu, 25 Aug 2011
ruby-1.9.2-p180 :021 > Date.today => Fri, 26 Aug 2011
Date.Today is the default method provided by ruby. Date.Yesterday though is not a ruby method but is provided by Rails as part of its core extensions.
Date.Yesterday returns Date.current.yesterday
Date.Current as quoted from rails documentation,
Returns Time.zone.today when Time.zone or config.time_zone are set, otherwise just returns Date.today
It seems this is the reason why you are getting the same date for both the methods.
It's problaby a TimeZone issue.
I'm developing in Spring Boot and I'm using the code below in the main class:
@PostConstruct
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
And when generate a Date, LocalDate, LocalDateTime or Instant use:
public static Instant getInstantNow() {
Clock utcClock = Clock.systemUTC();
return Instant.now(utcClock).minusSeconds(10800);//my local comparing to UTC in seg.
}
public static LocalDateTime getLocalDateTimeNow() {
ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
return LocalDateTime.from(nowBrasil);
}
public static LocalDate getLocalDateNow() {
ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
return LocalDate.from(nowBrasil);
}
精彩评论