Wireframe

날짜 계산 레시피

아주 짧은 기간 사이의 차이를 계산하는 법

Javascript

Date 객체를 빼면 그 사이의 밀리세컨드 값이 나온다.

var start = new Date();
/* perform some time-taking work... */
var end = new Date();
console.log(end - start);

Foundation(Swift)

-timeIntervalSinceDate: 메소드를 통해서 구할 수 있다. 결과로 나오는 NSTimeInterval은 경과 시간을 초단위로 센 값이며, 이전 이전 시점에 이후 시점을 비교하면 음수가 나온다.

NSDate *start = NSDate();
/* perform some time-taking job ... */
NSDate *end = NSDate();
NSLog(@"%d", [end timeIntervalSinceDate:start]);

혹은, 기준 시점을 ‘지금’으로 잡아서 다음과 같이할 수도 있다.

NSLog(@"%d", [start timeIntervalSinceNow] * -1);

Python

짧은 시간간격은 두 time.time 객체를 빼면 float 타입의 경과 시간이 나온다.

import time
a = time.time()
# perform a time-taking job...
b = time.time()
c = b - a # c is time interval in seconds

만약 datetime.datetime 객체 끼리 빼기 연산을 하면 timedelta 객체가 만들어진다. 이 때는 total_seconds()를 이용해서 경과 시간을 얻을 수 있다.

import datetime
a = datetime.datetime.now()
# perform a time-taking job...
b = datetime.datetime.now()
c = b - a
print type(c)
# <type 'datetime.timedelta'>
print c.total_seconds()
# 6.432
print c.seconds
# 6
print c.miliseconds
# 432000

특정 시점의 날짜 만들기

특정 날짜를 가리키는 문자열이나 년,월,일 정보를 이용해서 날짜 객체를 만드는 방법이다. 파이썬의 경우에는 문자열로부터 날짜를 만드는 기능은 표준 라이브러리에서 제공되지 않는다.

Cocoa

NSDatedateWithString:을 이용할 수 있다. 단 OSX10.10 부터는 이 방법이 권장되지 않는다. 대신에 NSDateFormatterdateFromString:을 쓰라고 한다.

NSDate *lastChristmas = [NSDate dateWithStrnig:@"2014-12-25 00:00:00 -0900"];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy.MM.dd";
NSDate *thisChristmas = [formatter dateFromString:@"2015.12.25"];

Swift 인터페이스에서는 실패하는 경우 nil이 나온다는 점만 고려하면 동일하다.

let a:NSDate? = NSDate(string:"2015-12-25 00:00:00 +0900")
let f = NSDateFormatter()
f.dateFormat = "yyyy.MM.dd"
let c:NSDate? = f.dateFromString("1970.12.25")

그외에 데이터 콤포넌트를 통해서 날짜를 만드려면 역시 달력이 필요하다. 날짜 콤포넌트에 각 년, 월, 일을 지정하고 NSCalendar 객체의 -dateFromComponents:를 통해서 날짜를 얻을 수 있다.

let cal = NSCalendar(calendarIdentifier:NSGregorianCalendar)!
let comps = NSDateComponents()
comps.year = 2015
comps.month = 12
comps.day = 25
let this_xmas:NSDate? = cal.dateFromComponent(comps)

Python

datetime.date, datetime.datetime 객체를 쓴다. 참고로 datetime.datetime.date()를 통해서 date 객체만 분리해낼 수 있다.

import datetime
last_christmas = datetime.date(2014, 12, 25)

Javascript

Date() 컨스트럭터에 문자열이나 년, 월, 일 값을 넣어서 만든다. 이 때 ‘월’은 0~11 범위이다. 헷갈림을 방지하기 위해서 자바스크립트에서는 yyyy-MM-dd 포맷의 문자열을 사용하는 편이 훨신 낫다.

var this_xmas = new Date("2015-12-25")
var wring_xmas = new Date(2015, 12, 25)
// "2016-01-25" 을 생성한다.

특정일자의 요일 구하기

파이썬과 자바스크립트 모두 특정일자의 요일은 날짜 객체만 제대로 생성하면 그 날의 요일을 바로 구하는 메소드나 프로퍼티를 제공한다. Cocoa의 경우, 날짜 객체는 기준일시로부터 경과한 초 값일 뿐이며, 달력상의 계산을 위해서는 NSCalendarNSDateComponents를 사용해야 한다.

Cocoa

특정일자의 요일은 달력을 거쳐야만 결정될 수 있다. 코코아에서는 일요일이 1이며 토요일이 7이다. (1~7)

let cal = NSCalendar(calendarIdentifier:NSGregorianCalendar)!
let comps = NSDateComponents()
comps.year = 2015
comps.month = 12
comps.day = 25
let this_xmas = cal.dateFromComponents(comps)
let weekdayComps = cal.components(.WeekdayCalendarUnit, fromDate:this_xmas!)
print(weekdayComps.weekday)

Python

datetime.date 객체의 weekday() 속성이 요일을 바로 가리킨다. 월요일이 0이다.

import datetime.date
this_xmas = datetime.date(2015, 12, 25)
print this_xmas.weekday()
4
# 금요일 맞습니다.

Javascript

Date 객체의 getDay() 의 결과가 요일이다. 일요일이 0이다.

긴 날짜의 거리 구하기

예를 들어 1992년 크리스마스로부터 2015년 설날(2/19)까지는 몇일 차이가 날까? (혹은 몇 개월하고 몇일 내지는 몇 년 몇 개월 몇 일) 날짜 비교 계산이 가장 불편해 보였던 코코아는 이 문제를 아주 쉽게 풀어낼 수 있다.

let cal = NSCalendar(calendarIdentifier:NSGregorianCalendar)!
let f = NSDateFormatter()
f.dateFormat = "yyyy-MM-dd"
let start = f.dateFromString("1992-12-25")!
let end = f.dateFromString("2015-02-19")!
let flags1:NSCalendarUnit = .DayCalendarUnit
let flags2:NSCalendarUnit = .DayCalendarUnit | .MonthCalendarUnit
let flags3:NSCalendarUnit = .DayCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit
let diff1 = cal.components(flags1, fromDate:start, toDate:end, options:NSCalendarOptions(0))
let diff2 = cal.components(flags2, fromDate:start, toDate:end, options:NSCalendarOptions(0))
let diff3 = cal.components(flags3, fromDate:start, toDate:end, options:NSCalendarOptions(0))
println("(diff1.day) days")
println("(diff2.month) month(s), (diff2.day) days")
println("(diff3.year) years, (diff3.month) month(s), (diff3.day) days")

비교하고자 하는 결과의 단위를 컴포넌트로 만들어서 비교하면 간단히 답이 나오게 된다.

파이썬과 자바 스크립트는 앞서 사용한 초 단위에 1000*60*60*24를 나눠서 몇 일 차이인지는 계산할 수 있으나, 몇 개월 혹은 몇 년이 들어가는 단위는 매우 계산이 어렵다. (한 달의 길이가 일정하지 않으므로)

N 일 후 구하기

Swift

let cal = NSCalendar(calendarIdentifier:NSGregorianCalendar)!
let f = NSDateFormatter()
f.dateFormat = "yyyy-MM-dd"
let start = f.dateFromString("1992-12-25")!
let offset = NSDateComponents()
offset.day = 3
let d3 = cal.dateByAddingComponents(offset, toDate:start, options:NSCalendarOptions(0))
if d3 != nil {
    println(d3!)
}

Javascript

var start = new Date('1992-12-25')
start.setDate(start.getDate() + 3);

Python

datetime 간의 차이가 timedelta이므로 datetimetimedelta를 더하면 그 날을 구할 수 있다.

import datetime
start = datetime.datetime(1992, 12, 25, 0, 0, 0)
offset = datetime.timedelta(days=3)
end = start + offset
Exit mobile version