I have an NSDate object and I want to set it to an arbitrary time (say, midnight) so that I can use the timeIntervalSince1970 function to retrieve data consistently without worrying about the time when the object is created.
I've tried using an NSCalendar and modifying its components by using some Objective-C methods, like this:
let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let components: NSDateComponents = cal.components(NSCalendarUnit./* a unit of time */CalendarUnit, fromDate: date)
let newDate: NSDate = cal.dateFromComponents(components)
The problem with the above method is that you can only set one unit of time (/* a unit of time */), so you could only have one of the following be accurate:
Day
Month
Year
Hours
Minutes
Seconds
Is there a way to set hours, minutes, and seconds at the same time and retain the date (day/month/year)?
Your statement
The problem with the above method is that you can only set one unit of
time ...
is not correct. NSCalendarUnit conforms to the RawOptionSetType protocol which
inherits from BitwiseOperationsType. This means that the options can be bitwise
combined with & and |.
In Swift 2 (Xcode 7) this was changed again to be
an OptionSetType which offers a set-like interface, see
for example Error combining NSCalendarUnit with OR (pipe) in Swift 2.0.
Therefore the following compiles and works in iOS 7 and iOS 8:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
// Swift 1.2:
let components = cal.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
// Swift 2:
let components = cal.components([.Day , .Month, .Year ], fromDate: date)
let newDate = cal.dateFromComponents(components)
(Note that I have omitted the type annotations for the variables, the Swift compiler
infers the type automatically from the expression on the right hand side of
the assignments.)
Determining the start of the given day (midnight) can also done
with the rangeOfUnit() method (iOS 7 and iOS 8):
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var newDate : NSDate?
// Swift 1.2:
cal.rangeOfUnit(.CalendarUnitDay, startDate: &newDate, interval: nil, forDate: date)
// Swift 2:
cal.rangeOfUnit(.Day, startDate: &newDate, interval: nil, forDate: date)
If your deployment target is iOS 8 then it is even simpler:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
Update for Swift 3 (Xcode 8):
let date = Date()
let cal = Calendar(identifier: .gregorian)
let newDate = cal.startOfDay(for: date)
Yes.
You don't need to fiddle with the components of the NSCalendar at all; you can simply call the dateBySettingHour method and use the ofDate parameter with your existing date.
let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let newDate: NSDate = cal.dateBySettingHour(0, minute: 0, second: 0, ofDate: date, options: NSCalendarOptions())!
For Swift 3:
let date: Date = Date()
let cal: Calendar = Calendar(identifier: .gregorian)
let newDate: Date = cal.date(bySettingHour: 0, minute: 0, second: 0, of: date)!
Then, to get your time since 1970, you can just do
let time: NSTimeInterval = newDate.timeIntervalSince1970
dateBySettingHour was introduced in OS X Mavericks (10.9) and gained iOS support with iOS 8.
Declaration in NSCalendar.h:
/*
This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time.
If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date).
The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course.
*/
- (NSDate *)dateBySettingHour:(NSInteger)h minute:(NSInteger)m second:(NSInteger)s ofDate:(NSDate *)date options:(NSCalendarOptions)opts NS_AVAILABLE(10_9, 8_0);
Here's an example of how you would do it, without using the dateBySettingHour function (to make sure your code is still compatible with iOS 7 devices):
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:now];
NSDate* midnightLastNight = [gregorian dateFromComponents:dateComponents];
Yuck.
There is a reason why I prefer coding in C#...
Anyone fancy some readable code..?
DateTime midnightLastNight = DateTime.Today;
;-)
Swift 5+
let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())
Swift iOS 8 and up: People tend to forget that the Calendar and DateFormatter objects have a TimeZone. If you do not set the desired timzone and the default timezone value is not ok for you, then the resulting hours and minutes could be off.
Note: In a real app you could optimize this code some more.
Note: When not caring about timezones, the results could be OK on one device, and bad on an other device just because of different timezone settings.
Note: Be sure to add an existing timezone identifier! This code does not handle a missing or misspelled timezone name.
func dateTodayZeroHour() -> Date {
var cal = Calendar.current
cal.timeZone = TimeZone(identifier: "Europe/Paris")!
return cal.startOfDay(for: Date())
}
You could even extend the language. If the default timezone is fine for you, do not set it.
extension Date {
var midnight: Date {
var cal = Calendar.current
cal.timeZone = TimeZone(identifier: "Europe/Paris")!
return cal.startOfDay(for: self)
}
var midday: Date {
var cal = Calendar.current
cal.timeZone = TimeZone(identifier: "Europe/Paris")!
return cal.date(byAdding: .hour, value: 12, to: self.midnight)!
}
}
And use it like this:
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "Europe/Paris")
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
let midnight = Date().midnight
let midnightString = formatter.string(from: midnight)
let midday = Date().midday
let middayString = formatter.string(from: midday)
let wheneverMidnight = formatter.date(from: "2018/12/05 08:08:08")!.midnight
let wheneverMidnightString = formatter.string(from: wheneverMidnight)
print("dates: \(midnightString) \(middayString) \(wheneverMidnightString)")
The string conversions and the DateFormatter are needed in our case for some formatting and to move the timezone since the date object in itself does not keep or care about a timezone value.
Watch out! The resulting value could differ because of a timezone offset somewhere in your calculating chain!
Just in case someone is looking for this:
Using SwiftDate you could just do this:
Date().atTime(hour: 0, minute: 0, second: 0)
In my opinion, the solution, which is easiest to verify, but perhaps not the quickest, is to use strings.
func set( hours: Int, minutes: Int, seconds: Int, ofDate date: Date ) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let newDateString = "\(dateFormatter.string(from: date)) \(hours):\(minutes):\(seconds)"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.date(from: newDateString)
}
func resetHourMinuteSecond(date: NSDate, hour: Int, minute: Int, second: Int) -> NSDate{
let nsdate = NSCalendar.currentCalendar().dateBySettingHour(hour, minute: minute, second: second, ofDate: date, options: NSCalendarOptions(rawValue: 0))
return nsdate!
}
Use the current calendar to get the start of the day for the current time.
let today = Calendar.current.startOfDay(for: Date())
This question already has answers here:
TimeZone changed while converting string to Date
(2 answers)
NSDate() or Date() shows the wrong time
(2 answers)
Getting date from [NSDate date] off by a few hours
(3 answers)
Swift convert string to date output wrong date
(4 answers)
Closed 1 year ago.
my string value is "2021.09.28 23:39".
but converted date is Optional(2021-09-28 14:39:00 +0000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy.MM.dd HH:mm"
dateFormatter.locale = Locale(identifier: "ko_kr")
dateFormatter.timeZone = TimeZone(abbreviation: "KST")
let date = dateFormatter.date(from: "2021.09.28 23:39")
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date!)
This is working correctly.
The KST timezone is UTC +9.
So... a time of 23:39 in the time zone KST is the same moment in time as the time 14:39 in UTC.
You output of Optional(2021-09-28 14:39:00 +0000) shows the timezone of +0000 and so is a displayed as a UTC time.
This question already has answers here:
Getting date from [NSDate date] off by a few hours
(3 answers)
Closed 3 years ago.
Converting from string to date and date to string time format is changing the original data.
Tried with dateComponents as well by giving the hour and minute
var calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: calFrom)
calendar.timeZone = .current
// Specify date components
var dateComponents:DateComponents = calendar.dateComponents([.year, .month, .day, .hour], from: Date())
dateComponents.year = components.year
dateComponents.month = components.month
dateComponents.day = components.day
dateComponents.hour = 08//Cutomised hour
dateComponents.minute = 34//Cutomised Minutes
// Create date from components
let someDateTime = calendar.date(from: dateComponents)
print(someDateTime!)
Actual Output:
2019-04-02 03:04:00 +0000
Expected Output:
2019-04-02 08:34:00 +0000
I tried with below code as well. Converting the date to String and manually appending the hour and minutes to the string and converting back to the date.
let calFrom = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
var calFromDate = formatter.string(from: calFrom)
calFromDate = calFromDate + " 09" + ":30"
print(calFromDate)
//Output 02/04/2019 09:30
formatter.dateFormat = "dd/MM/yyyy hh:mm"
formatter.locale = Locale.current// set locale to reliable US_POSIX
let date1 = formatter.date(from: calFromDate)
print(date1!)
Actual Output:
2019-04-02 04:00:00 +0000
Expected Output:
02/04/2019 09:30
How to get the exact time that has given in the output?
Date used to update the hour and minute components has UTC timezone so calendar should also have the same timeZone as below,
calendar.timeZone = TimeZone(abbreviation: "UTC")!
This question already has answers here:
NSDate timeIntervalSince1970 not working in Swift? [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to convert milliseconds to date string in swift 3,i tried by setting date fomatter but i am not getting current date string.
var milliseconds=1477593000000
let date = NSDate(timeIntervalSince1970: TimeInterval(milliseconds))
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
print(formatter.string(from: date as Date))
output:
22-01-48793 01:30:00
Try this,
var date = Date(timeIntervalSince1970: (1477593000000 / 1000.0))
print("date - \(date)")
You will get output as date :
date - 2016-10-27 18:30:00 +0000
How about trying this -
let milisecond = 1479714427
let dateVar = Date.init(timeIntervalSinceNow: TimeInterval(milisecond)/1000)
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
print(dateFormatter.string(from: dateVar))
Have a look at the documentation of NSDate:
convenience init(timeIntervalSince1970 secs: TimeInterval)
Returns an NSDate object initialized relative to the current date and time by a given number of seconds.
Just convert your milliseconds to seconds and you should get the correct date.
I need to get previous 5 years of GMT +08:00 timezone but I'm having trouble of getting the correct timezone.
let today = NSDate()
let gregorian = NSCalendar(calendarIdentifier: NSGregorianCalendar)
gregorian?.timeZone = NSTimeZone(forSecondsFromGMT: 60*60*8)
let offsetComponents = NSDateComponents()
offsetComponents.year = years
let nYearsDate: NSDate = gregorian!.dateByAddingComponents(offsetComponents, toDate: today, options: NSCalendarOptions(0))!
println("getNYearsDate: \(nYearsDate)")
I am getting 2010-07-23 11:44:47 +0000
instead of 2010-07-23 00:00:00 +0800
I need to get
2010-07-23 00:00:00 +0800 and 2010-07-23 23:59:59 +0800
is there anyway to achieve this in Swift and iOS 7.1 above?
You need to reset the time as well. Date periods are also best modeled with NSDateComponents.
// a little trick to get all calendar unit masks
let kAllCalendarUnits = NSCalendarUnit(rawValue: UInt.max)
// normalize the date
let components = NSCalendar.currentCalendar().components(
kAllCalendarUnits, fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
let dateAtStartOfDay = NSCalendar.currentCalendar().dateFromComponents(components)!
// subtract 5 years
var period = NSDateComponents()
period.year = -5
let finalDate = NSCalendar.currentCalendar().dateByAddingComponents(period,
toDate: dateAtStartOfDay, options: [])!
Note that the method with date components will give you the correct day, regardless if the period contains one or two leap years.
The rest is just a question of how to display this date. This is done with NSDateFormatter. Eg.:
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 60 * 60 * 8)
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss Z"
formatter.stringFromDate(finalDate)
// "2010-07-23 6:00:00 +0800"
In case you are wondering why it says "6:00" instead of "8:00": I ran this code with my machine set to GMT+1, plus summer time +1. Obviously, to get "0:00" you have to subtract the desired time difference again, but that would be 8 hours earlier in the GMT time zone.