NSDate가 오늘인지 확인하는 방법은 무엇입니까?
확인하는 방법NSDate
오늘의 것입니까?
처음 10자를 사용하여 확인하곤 했습니다.[aDate description]
.[[aDate description] substringToIndex:10]
다음과 같은 문자열을 반환합니다."YYYY-MM-DD"
그래서 저는 그 끈과 그 끈을 비교했습니다.[[[NSDate date] description] substringToIndex:10]
.
더 빠르고 깔끔하게 점검할 수 있는 방법이 있습니까?
감사해요.
macOS 10.9+ & iOS 8+에서는 NSC 캘린더/캘린더에 정확히 이를 수행하는 방법이 있습니다!
- (BOOL)isDateInToday:(NSDate *)date
그래서 당신은 간단하게.
목표-C:
BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];
스위프트 3:
let today = Calendar.current.isDateInToday(date)
날짜 구성 요소를 비교할 수 있습니다.
NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
if([today day] == [otherDay day] &&
[today month] == [otherDay month] &&
[today year] == [otherDay year] &&
[today era] == [otherDay era]) {
//do stuff
}
편집:
저는 스테판의 방법이 더 마음에 들어요, 만약 다음과 같은 진술이 나온다면 더 깨끗하고 이해하기 쉬울 것이라고 생각합니다.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:components];
components = [cal components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:aDate];
NSDate *otherDate = [cal dateFromComponents:components];
if([today isEqualToDate:otherDate]) {
//do stuff
}
크리스, 당신의 제안을 통합했습니다.저는 어떤 시대인지 찾아봐야 했습니다. 그래서 모르는 사람들은 그것이 BC와 AD를 구분합니다.대부분의 사람들에게 이것은 아마도 불필요한 것이겠지만, 확인하기도 쉽고 어느 정도 확실성을 더해주기 때문에, 저는 그것을 포함시켰습니다.속도를 높이려면, 어쨌든 이것은 좋은 방법이 아닐 것입니다.
참고 SO에 대한 많은 답변과 마찬가지로 7년 후에는 완전히 구식입니다.Swift에서 지금은 그냥 사용하세요..isDateInToday
이것은 질문의 파생물이지만 "오늘" 또는 "어제"로 NSDate를 인쇄하려면 기능을 사용합니다.
- (void)setDoesRelativeDateFormatting:(BOOL)b
NS Date Formatter
저는 오늘 날짜를 자정으로 정규화하고 두 번째 날짜를 자정으로 정규화한 후 동일한 NSDate인지 비교하려고 합니다.
Apple의 예에서 오늘 자정으로 표준화하는 방법은 다음과 같습니다. 두 번째 날짜에도 동일하게 하고 비교해 보십시오.
NSCalendar * gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * components =
[gregorian components:
(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)
fromDate:[NSDate date]];
NSDate * today = [gregorian dateFromComponents:components];
메기_맨의 제안을 빠르게 확장하는 작업:
extension Date {
var isToday: Bool {
Calendar.current.isDateInToday(self)
}
}
구성 요소, 지우기 등을 조작할 필요가 없습니다.
NSC 일정관리는 기존 날짜의 특정 시간 단위의 시작을 가져오는 방법을 제공합니다.
이 코드는 오늘과 다른 날짜의 시작을 얻고 그것을 비교할 것입니다.로 평가된다면,NSOrderedSame
두 날짜가 모두 같은 날입니다. 그래서 오늘입니다.
NSDate *today = nil;
NSDate *beginningOfOtherDate = nil;
NSDate *now = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&today interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfOtherDate interval:NULL forDate:beginningOfOtherDate];
if([today compare:beginningOfOtherDate] == NSOrderedSame) {
//otherDate is a date in the current day
}
extension NSDate {
func isToday() -> Bool {
let cal = NSCalendar.currentCalendar()
var components = cal.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components([.Era, .Year, .Month, .Day], fromDate:self)
let otherDate = cal.dateFromComponents(components)!
return today.isEqualToDate(otherDate)
}
Swift 2.0에서 근무했습니다.
최고의 답변의 빠른 버전:
let cal = NSCalendar.currentCalendar()
var components = cal.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components([.Era, .Year, .Month, .Day], fromDate:aDate);
let otherDate = cal.dateFromComponents(components)!
if(today.isEqualToDate(otherDate)) {
//do stuff
}
Apple의 문서 항목 "일정표 계산 수행"[link]을 참조하십시오.
해당 페이지의 목록 13은 일 사이의 자정 시간을 결정하기 위해 다음을 사용한다는 것을 나타냅니다.
- (NSInteger)midnightsFromDate:(NSDate *)startDate toDate:(NSDate *)endDate
{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSInteger startDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSEraCalendarUnit
forDate:startDate];
NSInteger endDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSEraCalendarUnit
forDate:endDate];
return endDay - startDay;
}
그런 다음 이 방법을 사용하여 0을 반환하는지 여부를 확인하여 이틀이 동일한지 여부를 확인할 수 있습니다.
현재 날짜와 현재 날짜 사이의 시간 간격을 확인할 수도 있습니다.
[myDate timeIntervalSinceNow]
myDate와 현재 날짜/시간 사이의 시간 간격(초)이 표시됩니다.
링크.
편집: 모든 사용자에게 참고:나는 [나의 데이트 시간]을 잘 알고 있습니다.IntervalSinceNow]는 myDate가 오늘인지 여부를 명확하게 확인하지 않습니다.
누군가 유사한 것을 찾고 있다면 [내 데이트 시간]을 위해 이 답변을 그대로 둡니다.IntervalSinceNow]는 유용하며 여기에서 찾을 수 있습니다.
최상의 답변을 기반으로 한 신속한 확장:
extension NSDate {
func isToday() -> Bool {
let cal = NSCalendar.currentCalendar()
if cal.respondsToSelector("isDateInToday:") {
return cal.isDateInToday(self)
}
var components = cal.components((.CalendarUnitEra | .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay), fromDate:NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components((.CalendarUnitEra | .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay), fromDate:self);
let otherDate = cal.dateFromComponents(components)!
return today.isEqualToDate(otherDate)
}
}
비교가 ▁to▁calls다▁if로 전화가 걸려옵니다.calendar:components:fromDate
시간이 많이 걸리기 시작합니다.제가 몇 가지 프로파일링을 해본 결과, 꽤 비싼 것 같습니다.
날짜를 가정해 .NSArray *datesToCompare
날과 이라고 요.NSDate *baseDate
그런 다음 다음과 같은 것을 사용할 수 있습니다(위의 답변에서 수정됨).
NSDate *baseDate = [NSDate date];
NSArray *datesToCompare = [NSArray arrayWithObjects:[NSDate date],
[NSDate dateWithTimeIntervalSinceNow:100],
[NSDate dateWithTimeIntervalSinceNow:1000],
[NSDate dateWithTimeIntervalSinceNow:-10000],
[NSDate dateWithTimeIntervalSinceNow:100000],
[NSDate dateWithTimeIntervalSinceNow:1000000],
[NSDate dateWithTimeIntervalSinceNow:50],
nil];
// determine the NSDate for midnight of the base date:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)
fromDate:baseDate];
NSDate* theMidnightHour = [calendar dateFromComponents:comps];
// set up a localized date formatter so we can see the answers are right!
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// determine which dates in an array are on the same day as the base date:
for (NSDate *date in datesToCompare) {
NSTimeInterval interval = [date timeIntervalSinceDate:theMidnightHour];
if (interval >= 0 && interval < 60*60*24) {
NSLog(@"%@ is on the same day as %@", [dateFormatter stringFromDate:date], [dateFormatter stringFromDate:baseDate]);
}
else {
NSLog(@"%@ is NOT on the same day as %@", [dateFormatter stringFromDate:date], [dateFormatter stringFromDate:baseDate]);
}
}
출력:
Nov 23, 2011 1:32:00 PM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 1:33:40 PM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 1:48:40 PM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 10:45:20 AM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 24, 2011 5:18:40 PM is NOT on the same day as Nov 23, 2011 1:32:00 PM
Dec 5, 2011 3:18:40 AM is NOT on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 1:32:50 PM is on the same day as Nov 23, 2011 1:32:00 PM
위의 많은 대답들보다 더 쉬운 방법이 있습니다!
NSDate *date = ... // The date you wish to test
NSCalendar *calendar = [NSCalendar currentCalendar];
if([calendar isDateInToday:date]) {
//do stuff
}
NSDate 범주로 재작업할 수 있지만 다음을 사용했습니다.
// Seconds per day (24h * 60m * 60s)
#define kSecondsPerDay 86400.0f
+ (BOOL) dateIsToday:(NSDate*)dateToCheck
{
// Split today into components
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* comps = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit)
fromDate:[NSDate date]];
// Set to this morning 00:00:00
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate* theMidnightHour = [gregorian dateFromComponents:comps];
[gregorian release];
// Get time difference (in seconds) between date and then
NSTimeInterval diff = [dateToCheck timeIntervalSinceDate:theMidnightHour];
return ( diff>=0.0f && diff<kSecondsPerDay );
}
(그러나 원래 질문과 같이 두 개의 날짜 문자열을 비교하면 거의 '깨끗하게' 느껴집니다.)
iOS7 및 이전 버전의 경우:
//this is now => need that for the current date
NSDate * now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents * components = [calendar components:( NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: now];
[components setMinute:0];
[components setHour:0];
[components setSecond:0];
//this is Today's Midnight
NSDate *todaysMidnight = [calendar dateFromComponents: components];
//now timeIntervals since Midnight => in seconds
NSTimeInterval todayTimeInterval = [now timeIntervalSinceDate: todaysMidnight];
//now timeIntervals since OtherDate => in seconds
NSTimeInterval otherDateTimeInterval = [now timeIntervalSinceDate: otherDate];
if(otherDateTimeInterval > todayTimeInterval) //otherDate is not in today
{
if((otherDateTimeInterval - todayTimeInterval) <= 86400) //86400 == a day total seconds
{
@"yesterday";
}
else
{
@"earlier";
}
}
else
{
@"today";
}
now = nil;
calendar = nil;
components = nil;
todaysMidnight = nil;
NSLog("Thank you :-)");
우리 에리카 사둔의 훌륭함을 확인하세요.NSDate extension
사용법이 매우 간단합니다.좋아요.
http://github.com/erica/NSDate-Extensions
이미 다음 게시물에 있습니다. https://stackoverflow.com/a/4052798/362310
Swift 2.2 및 iOS 8 이전 버전에서 작동하는 강제 포장 없이 정확하고 안전한 솔루션:
func isToday() -> Bool {
let calendar = NSCalendar.currentCalendar()
if #available(iOS 8.0, *) {
return calendar.isDateInToday(self)
}
let todayComponents = calendar.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
let dayComponents = calendar.components([.Era, .Year, .Month, .Day], fromDate:self)
guard let today = calendar.dateFromComponents(todayComponents),
day = calendar.dateFromComponents(dayComponents) else {
return false
}
return today.compare(day) == .OrderedSame
}
승인된 답변에 대한 제 2센트 답변 빌드이지만 최신 API도 지원합니다.참고: 저는 대부분의 타임 스탬프가 GMT이기 때문에 그레고리력을 사용하지만, 당신이 적합하다고 생각하는 대로 당신의 것을 바꿉니다.
func isDateToday(date: NSDate) -> Bool {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
if calendar.respondsToSelector("isDateInToday:") {
return calendar.isDateInToday(date)
}
let dateComponents = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay
let today = calendar.dateFromComponents(calendar.components(dateComponents, fromDate: NSDate()))!
let dateToCompare = calendar.dateFromComponents(calendar.components(dateComponents, fromDate: date))!
return dateToCompare == today
}
나의 해결책은 1970년 이후로 얼마나 많은 날들이 지나갔는지를 나눗셈으로 계산하고 정수 부분을 비교하는 것입니다.
#define kOneDay (60*60*24)
- (BOOL)isToday {
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSInteger days =[self timeIntervalSince1970] + offset;
NSInteger currentDays = [[NSDate date] timeIntervalSince1970] + offset;
return (days / kOneDay == currentDays / kOneDay);
}
NSDate *dateOne = yourDate;
NSDate *dateTwo = [NSDate date];
switch ([dateOne compare:dateTwo])
{
case NSOrderedAscending:
NSLog(@”NSOrderedAscending”);
break;
case NSOrderedSame:
NSLog(@”NSOrderedSame”);
break;
case NSOrderedDescending:
NSLog(@”NSOrderedDescending”);
break;
}
언급URL : https://stackoverflow.com/questions/2331129/how-to-determine-if-an-nsdate-is-today
'programing' 카테고리의 다른 글
프로그래밍 방식으로 연락처 액세스 요청 (0) | 2023.06.11 |
---|---|
여러 C/C++ 라이브러리를 하나로 결합하려면 어떻게 해야 합니까? (0) | 2023.06.11 |
yup의 물건을 사용하는 방법.타자기로 모양을 만들 수 있습니까? (0) | 2023.06.11 |
VBA에서 양식이 닫힐 때 코드 실행(Excel 2007) (0) | 2023.06.11 |
iPhone에서 프로그래밍 방식으로 메모리 사용량 검색 (0) | 2023.06.01 |