Подтвердить что ты не робот

Как получить дату без времени из NSDate?

Я хочу получить дату от NSDate и не нужно время. Пример:

NSDate* today = [NSDate date];  // want to give 20-06-2012 only

Я хочу получить дату сегодня, не показывая время и не использую ее в переменной NSDate или строковой переменной.

4b9b3361

Ответ 1

Если кто-то ищет это. Я использовал следующее:

NSDateComponents *components = [[NSCalendar currentCalendar] 
             components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit 
              fromDate:[NSDate date]];
NSDate *startDate = [[NSCalendar currentCalendar] 
             dateFromComponents:components];

Ответ 2

В плане производительности этот подход может быть лучше, если использовать NSDateFormatter или NSCalendar.

Swift 3

let timeInterval = floor(Date().timeIntervalSinceReferenceDate / 86400) * 86400
let newDate = Date(timeIntervalSinceReferenceDate: timeInterval)

Swift 2

let timeInterval = floor(NSDate().timeIntervalSinceReferenceDate / 86400) * 86400
let newDate = NSDate(timeIntervalSinceReferenceDate: timeInterval)

Вы также можете учитывать часовой пояс (эта функция является частью расширения NSDate):

Swift 3

extension Date {

    func dateWithoutTime() -> Date {
        let timeZone = TimeZone.current
        let timeIntervalWithTimeZone = self.timeIntervalSinceReferenceDate + Double(timeZone.secondsFromGMT())
        let timeInterval = floor(timeIntervalWithTimeZone / 86400) * 86400
        return Date(timeIntervalSinceReferenceDate: timeInterval)
    }

}

Swift 2

extension NSDate {

    func dateWithoutTime() -> NSDate {
        let timeZone = NSTimeZone.localTimeZone()
        let timeIntervalWithTimeZone = self.timeIntervalSinceReferenceDate + Double(timeZone.secondsFromGMT)
        let timeInterval = floor(timeIntervalWithTimeZone / 86400) * 86400
        return NSDate(timeIntervalSinceReferenceDate: timeInterval)
    }

}

Ответ 3

Использовать этот метод

- (NSString *)curentDateStringFromDate:(NSDate *)dateTimeInLine withFormat:(NSString *)dateFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

    [formatter setDateFormat:dateFormat];

    NSString *convertedString = [formatter stringFromDate:dateTimeInLine];

    return convertedString;
}

Используйте его как ниже

NSString *dateString = [self curentDateStringFromDate:[NSDate date] withFormat:@"dd-MM-yyyy"];

Ответ 4

Я реализовал расширение Swift, если кто-то заинтересован. Это даст вам текущую дату (в вашем часовом поясе) в 00:00:00 UTC, что, я думаю, означает текущую дату без времени.

Я думаю, что это лучше, чем @Murlakatam, потому что это не связано с беспорядочным использованием timeIntervalSinceReferenceDate, поэтому мы используем объекты даты в первую очередь.

extension NSDate
{
    // Calendar objects are expensive to create to it better to create and reuse only one.
    private static var cachedNoTimeZoneCalendar: NSCalendar = {
        let calendar = NSCalendar.currentCalendar()
        calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        return calendar
    }()

    func dateWithoutTime() -> NSDate?
    {
        let dateComponents = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: self)
        return NSDate.cachedNoTimeZoneCalendar.dateFromComponents(dateComponents)
    }
}