How to get the date without Time from NSDate?
In terms of performance this approach may be better than using NSDateFormatter or NSCalendar.
Swift 3, 4, 5
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)
You can also take into account time zone (this function is part of NSDate extension):
Swift 3, 4, 5
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)
}
}
I implemented a Swift extension if anyone is interested. This will give you the current date (in your timezone) at 00:00:00 UTC, which I think is the meaning of current date without time.
I think it's better than @Murlakatam's answer because it doesn't involve messing with the raw timeIntervalSinceReferenceDate
which is why we use date objects in the first place.
extension NSDate
{
// Calendar objects are expensive to create to it's 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)
}
}
Use This method
- (NSString *)curentDateStringFromDate:(NSDate *)dateTimeInLine withFormat:(NSString *)dateFormat {
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:dateFormat];
NSString *convertedString = [formatter stringFromDate:dateTimeInLine];
return convertedString;
}
Use it Like Below
NSString *dateString = [self curentDateStringFromDate:[NSDate date] withFormat:@"dd-MM-yyyy"];
In case someone else looks for this. I used the following:
NSDateComponents *components = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
NSDate *startDate = [[NSCalendar currentCalendar]
dateFromComponents:components];