[Ruby on Rails] Ruby Time.now vs Time.current
2021. 10. 21. 18:36
반응형
ruby에서 time zone 관련 요약
사용하지 말아야 하는 것 DON'T USE
* Time.now
* Date.Today
* Date.Today.to_time
* Time.parse("2021-10-21 18:19:20")
* Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")
사용해도 되는 것 DO USE
* Time.current
* 2.hours.ago
* Time.zone.today
* Date.current
* 1.day.from_now
* Time.zone.parse("2020-10-21 18:06:22")
* TIme.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone
Time zones in Rails
rails는 ruby와 같은 API를 제공하는데 rails에서 time zones 와 관련된 것을 볼 수 있다.
$ rails time:zones:all
* UTC -12:00 *
International Date Line West
...
* UTC +00:00 *
Casablanca
Dublin
Edinburgh
Lisbon
London
Monrovia
UTC
...
* UTC +09:00 *
Osaka
Sapporo
Seoul
Tokyo
Yakutsk
...
Three time zones
rails에서 3가지 time zones가 있다.
- system time
- application time
- database time
# This is the time on my machine, also commonly described as "system time" (시스템 타임)
> Time.now
=> 2015-07-04 17:53:23 -0400
# Let's set the time zone to be Fiji (피지의 타임존으로 등록해도)
> Time.zone = "Fiji"
=> "Fiji"
# But we still get my system time (여전히 시스템 타임이 출력)
> Time.now
=> 2015-07-04 17:53:37 -0400
# However, if we use `zone` first, we finally get the current time in Fiji (타임존을 등록)
> Time.zone.now
=> Sun, 05 Jul 2015 09:53:42 FJT +12:00
# We can also use `current` to get the same
> Time.current
=> Sun, 05 Jul 2015 09:54:17 FJT +12:00
# Or even translate the system time to application time with `in_time_zone`
> Time.now.in_time_zone
=> Sun, 05 Jul 2015 09:56:57 FJT +12:00
# Let's do the same with Date (we are still in Fiji time, remember?)
# This again is the date on my machine, system date
> Date.today
=> Sat, 04 Jul 2015
# But going through `zone` again, and we are back to application time
> Time.zone.today
=> Sun, 05 Jul 2015
# And gives us the correct tomorrow according to our application's time zone
> Time.zone.tomorrow
=> Mon, 06 Jul 2015
# Going through Rails' helpers, we get the correct tomorrow as well
> 1.day.from_now
=> Mon, 06 Jul 2015 10:00:56 FJT +12:00
[출처]
https://thoughtbot.com/blog/its-about-time-zones
728x90
반응형
'web > Ruby on Rails' 카테고리의 다른 글
Written by ner.o
개발자 네로의 개발 일기,
자바를 좋아합니다 !
댓글 개