Ruby Basic - 7

woolim park·2021년 3월 14일
0

Ruby Basic

목록 보기
7/9
post-thumbnail

Date and Time

  • 모든 시간은 1970년 1월 1일 이후로 부터 초로 계산되어 저장(Unix Timestamp)
  • 모든 시간은 초의 분수단위를 포함 (비교를 위해 사용)

Time

> Time.now
2021-03-14 22:00:03.771935371 +0100
> Time.now.to_i
1615755619
> Time.at(1615755619)
2021-03-14 22:00:19 +0100
> Time.new(year, month, day, hour, min, sec, utc_offset)
> Time.new(2018, 10, 31)

시간 연산

> tomorrow = Time.now + (60 * 60 * 24)
> next_week = Time.now + (60 * 60 * 24 * 7)
> next_year = Time.now + (60 * 50 * 24 * 365)

유용한 메소드

> now = Time.now
> now.year
> now.month
> now.day
> now.hour
> now.min
> now.sec
> now.nsec
> now.yday # day of the year
> now.wday # day of the week
> now.sunday?
> now.strftime(format...)
> now.zone
> now.utc?
> now.gmt?
> now.dst?
> now.gmt_offset
> now.getutc
> now.getlocal
> now.utc
> now.gmtime
> now.localtime

Date

time 과 비슷하지만 날짜만 필요한 경우 사용. Date class 는 Ruby Standard Library 에 속하므로 따로 require "date" 를 해줘야만 사용할 수 있다.

> require 'date'
> Date.today
> Date.today.month
> Date.new(2021, 3, 14)
> Date.today.to_time
> Time.now.to_date
> d = Date.today
> d.leap? # 윤년인지 아닌지
> d.cweek # calendar week
> d.cwday # calendar week day
> d.next_day
> d.next_month
> d.next_year
> d.prev_day
> d.prev_month
> d.prev_year
> d.gregorian?
> d.julian?

DateTime

  • DateTime class 는 Ruby Standard Library 에 속하므로 따로 require 'date' 해주어야 한다.
  • DateTime 은 Date 클래스의 서브클래스다.
  • DateTime 은 과거의 날짜를 추적하는데 적절하다.
> require 'date'
> DateTime.now
> DateTime.new(year, month, day, hour, min, sec, utc_offset)
> DateTime.now.to_time
> Time.now.to_datetime

Time 을 우선하여 사용하고 그 외 기타 기능이 필요하면 Date, DateTime 을 사용한다.

profile
Javascript Developer

0개의 댓글