I have an app the records the start time and date using the Calendar.component for each individual calendar component (i.e. let hour = calendar.component(.hour, from:date)) and sends the data to a Google form after another button is pressed. When the Minutes or seconds begins with a 0, the 0 gets dropped and I get a result like this: 4:2:3 for what should be 04:02:03.
Here is the code:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from:date)
let minutes = calendar.component(.minute, from:date)
let seconds = calendar.component(.second, from:date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
startTime = "\(hour):\(minutes):\(seconds)"
startDate = "\(month)/\(day)/\(year)"
You don't need Calendar & Date Object Separately. Date Object will do both.
DateFormatter is the correct way of doing this.
// unnecessary code
/* let calendar = Calendar.current
let hour = calendar.component(.hour, from:date)
let minutes = calendar.component(.minute, from:date)
let seconds = calendar.component(.second, from:date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
*/
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss"
var startTime = dateFormatter.string(from: date)
dateFormatter.dateFormat = "M/dd/yyyy"
var startDate = dateFormatter.string(from: date)
Related
All,
I have a date format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" and I need to set the millisecond value, but date component does not provide millisecond attribute.
Below is my code for setting custom values in hour, minute, second. I also need to set millisecond to 0/999 value.
static func getToadyStartInUTC() -> String{
let todaydate = Date()
let formatter = DateFormatter()
var components = Calendar.current.dateComponents([.year, .month, .day, .hour], from: todaydate)
components.hour = 0
components.minute = 0
components.second = 0
let calendar = Calendar.current
let startDate = calendar.date(from: components)!
print("\(startDate)")
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return formatter.string(from: startDate)
}
How can I set the millisecond value in date component?
An alternative solution with Calendar API to get startDate and ISO8601DateFormatter
static func getToadyStartInUTC() -> String {
let todaydate = Date()
var calendar = Calendar.current
let timeZone = TimeZone(secondsFromGMT: 0)!
calendar.timeZone = timeZone
let startDate = calendar.startOfDay(for: todaydate)
var components = calendar.dateComponents(in: timeZone, from: startDate)
components.nanosecond = 999000000
let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds)
return formatter.string(from: components.date!)
}
let todaydate = Date()
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")
let startDate = calendar.startOfDay(for: todaydate)
var components = calendar.dateComponents(in: timeZone, from: startDate)
components.nanosecond = 999000000
let formatter = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.string(from: components.date!)
I am getting year,month and day from a given date in this way.
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day=components.day
But I'm getting one day ahead from my current day. How can I solve this?
let date = Date().description(with: Locale.current)
print("date ---> \(date)")
Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time
I'm getting perfect system/local time.
You code is working,
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)
let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")
Result: day = Optional(20) hour = Optional(16) minute = Optional(35)
Get Local Date and Time
Swift 5:
let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()
As per the documentation:
If you want “date information in a given time zone” in order to
display it, you should use DateFormatter to format the date.
eg:
// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today)) // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today)) // prints "06\n"
I am trying to get current date in Swift using NSDate(). When I create breakpoint and stop application, I can see that there is 3 hours difference with devices' system time. Application is running on real iPhone. How to fix this?
I also wrote the following in App Delegate to be sure:
NSTimeZone.setDefaultTimeZone(NSTimeZone(name: "Europe/Kiev")!)
But it still does not work.
It doesn't return the wrong time. It returns exactly the right time. NSDate doesn't have any timezone information. Right now, my computer and your computer will report the exact same time when we call NSDate ().
NSLog displays NSDate in UTC. That's just what it displays. So if we both call NSLog right now, your computer will log the same date and time as mine. Because it is the same date and time.
If you want to process an NSDate (for example, to display the date and time to a user) you use an NSCalendar. The NSCalendar translates between NSDate, which is the same everywhere in the world, to the values that you want to display in your user interface, which will be different in London or in Kiev. If I look on my watch right now, I will see a different time than you see on your watch, and that is what NSCalendar is there for.
Here is the conversion for swift 3.0 :
func getCurrentLocalDate()-> Date {
var now = Date()
var nowComponents = DateComponents()
let calendar = Calendar.current
nowComponents.year = Calendar.current.component(.year, from: now)
nowComponents.month = Calendar.current.component(.month, from: now)
nowComponents.day = Calendar.current.component(.day, from: now)
nowComponents.hour = Calendar.current.component(.hour, from: now)
nowComponents.minute = Calendar.current.component(.minute, from: now)
nowComponents.second = Calendar.current.component(.second, from: now)
nowComponents.timeZone = TimeZone(abbreviation: "GMT")!
now = calendar.date(from: nowComponents)!
return now as Date
}
Also worth checking if your test device Date/Time is set to an older date.
For Swift 2.2 this function did the trick for me:
func getCurrentLocalDate()-> NSDate {
var now = NSDate()
let nowComponents = NSDateComponents()
let calendar = NSCalendar.currentCalendar()
nowComponents.year = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: now)
nowComponents.month = NSCalendar.currentCalendar().component(NSCalendarUnit.Month, fromDate: now)
nowComponents.day = NSCalendar.currentCalendar().component(NSCalendarUnit.Day, fromDate: now)
nowComponents.hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: now)
nowComponents.minute = NSCalendar.currentCalendar().component(NSCalendarUnit.Minute, fromDate: now)
nowComponents.second = NSCalendar.currentCalendar().component(NSCalendarUnit.Second, fromDate: now)
nowComponents.timeZone = NSTimeZone(abbreviation: "GMT")
now = calendar.dateFromComponents(nowComponents)!
return now
}
If you want a different timezone you can change it directly, or even better, pass it as a function parameter.
You can also use Locale to get current time and date.
let today = NSDate()
let locale = NSLocale.current
print("Time of today: \(today.description(with: locale))")
This func returns Now in a current time zone.
func convertDate(date:Date) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var comp = DateComponents()
let calendar = Calendar.current
comp.year = Calendar.current.component(.year, from: date)
comp.month = Calendar.current.component(.month, from: date)
comp.day = Calendar.current.component(.day, from: date)
comp.hour = Calendar.current.component(.hour, from: date)
comp.minute = Calendar.current.component(.minute, from: date)
comp.second = Calendar.current.component(.second, from: date)
comp.timeZone = TimeZone(abbreviation: "GMT")
var dateFromCalendar = Date()
if let calendarDate = calendar.date(from: comp) {
dateFromCalendar = calendarDate
}
return dateFromCalendar
}
To use:
let now = Date()
let convertedDate = convertDate(date: now)
I am trying to get current date in Swift using NSDate(). When I create breakpoint and stop application, I can see that there is 3 hours difference with devices' system time. Application is running on real iPhone. How to fix this?
I also wrote the following in App Delegate to be sure:
NSTimeZone.setDefaultTimeZone(NSTimeZone(name: "Europe/Kiev")!)
But it still does not work.
It doesn't return the wrong time. It returns exactly the right time. NSDate doesn't have any timezone information. Right now, my computer and your computer will report the exact same time when we call NSDate ().
NSLog displays NSDate in UTC. That's just what it displays. So if we both call NSLog right now, your computer will log the same date and time as mine. Because it is the same date and time.
If you want to process an NSDate (for example, to display the date and time to a user) you use an NSCalendar. The NSCalendar translates between NSDate, which is the same everywhere in the world, to the values that you want to display in your user interface, which will be different in London or in Kiev. If I look on my watch right now, I will see a different time than you see on your watch, and that is what NSCalendar is there for.
Here is the conversion for swift 3.0 :
func getCurrentLocalDate()-> Date {
var now = Date()
var nowComponents = DateComponents()
let calendar = Calendar.current
nowComponents.year = Calendar.current.component(.year, from: now)
nowComponents.month = Calendar.current.component(.month, from: now)
nowComponents.day = Calendar.current.component(.day, from: now)
nowComponents.hour = Calendar.current.component(.hour, from: now)
nowComponents.minute = Calendar.current.component(.minute, from: now)
nowComponents.second = Calendar.current.component(.second, from: now)
nowComponents.timeZone = TimeZone(abbreviation: "GMT")!
now = calendar.date(from: nowComponents)!
return now as Date
}
Also worth checking if your test device Date/Time is set to an older date.
For Swift 2.2 this function did the trick for me:
func getCurrentLocalDate()-> NSDate {
var now = NSDate()
let nowComponents = NSDateComponents()
let calendar = NSCalendar.currentCalendar()
nowComponents.year = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: now)
nowComponents.month = NSCalendar.currentCalendar().component(NSCalendarUnit.Month, fromDate: now)
nowComponents.day = NSCalendar.currentCalendar().component(NSCalendarUnit.Day, fromDate: now)
nowComponents.hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: now)
nowComponents.minute = NSCalendar.currentCalendar().component(NSCalendarUnit.Minute, fromDate: now)
nowComponents.second = NSCalendar.currentCalendar().component(NSCalendarUnit.Second, fromDate: now)
nowComponents.timeZone = NSTimeZone(abbreviation: "GMT")
now = calendar.dateFromComponents(nowComponents)!
return now
}
If you want a different timezone you can change it directly, or even better, pass it as a function parameter.
You can also use Locale to get current time and date.
let today = NSDate()
let locale = NSLocale.current
print("Time of today: \(today.description(with: locale))")
This func returns Now in a current time zone.
func convertDate(date:Date) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var comp = DateComponents()
let calendar = Calendar.current
comp.year = Calendar.current.component(.year, from: date)
comp.month = Calendar.current.component(.month, from: date)
comp.day = Calendar.current.component(.day, from: date)
comp.hour = Calendar.current.component(.hour, from: date)
comp.minute = Calendar.current.component(.minute, from: date)
comp.second = Calendar.current.component(.second, from: date)
comp.timeZone = TimeZone(abbreviation: "GMT")
var dateFromCalendar = Date()
if let calendarDate = calendar.date(from: comp) {
dateFromCalendar = calendarDate
}
return dateFromCalendar
}
To use:
let now = Date()
let convertedDate = convertDate(date: now)
How would I get the hour of the day in Swift.
I have tried NSCalendar and NSDateComponents, but I'm afraid I'm just starting with Swift.
Swift 5.0 / 4.0 / 3.0
let hour = Calendar.current.component(.hour, from: Date())
Or, if you're interested in 12 hour AM/PM date format, then use NSDateFormatter
let formatter = DateFormatter()
formatter.dateFormat = "hh a" // "a" prints "pm" or "am"
let hourString = formatter.string(from: Date()) // "12 AM"
If you want minutes, seconds and others, do as following
let date = Date() // save date, so all components use the same date
let calendar = Calendar.current // or e.g. Calendar(identifier: .persian)
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
Check out available components on Apple docs:
.era, .year, .month, .day, .hour, .minute, .second,
.weekday, .weekdayOrdinal, .quarter, weekOfMonth, .weekOfYear,
.yearForWeekOfYear, .nanosecond, .calendar, .timezone
Swift 2.0
let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
Swift 1.0
let hour = NSCalendar.currentCalendar().component(.CalendarUnitHour, fromDate: NSDate())
Swift 3:
let date = Date()// Aug 25, 2017, 11:55 AM
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date) //11
let minute = calendar.component(.minute, from: date) //55
let sec = calendar.component(.second, from: date) //33
let weekDay = calendar.component(.weekday, from: date) //6 (Friday)
Get any of component available from the API below
public enum Component {
case era
case year
case month
case day
case hour
case minute
case second
case weekday
case weekdayOrdinal
case quarter
case weekOfMonth
case weekOfYear
case yearForWeekOfYear
case nanosecond
case calendar
case timeZone
}
Swift 2:
let currentHour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
This could be enough :
let currentDate = NSDate() // You can input the custom as well
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: currentDate)
let currentHour = components.hour // You can play around with the ""components""
If you want the current hour in a String, this is as short and readable I could think of.
let formatter = NSDateFormatter()
formatter.dateFormat = "HH"
let timeString = formatter.stringFromDate(NSDate())
Finally I was able to find the easiest solution after struggling for a time
let dateComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.HourCalendarUnit, fromDate: NSDate())
let nHourOfDay = dateComponents.hour
For Swift 2.0:
let hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: NSDate())
Here is a reference example for how I do it (DateUtils.swift) -
Example Use:
let today = DateUtils.getToday();
let hr = DateUtils.getHours(today);
let min = DateUtils.getMinutes(today);
... (etc.) ...
DateUtils.swift:
//Field wrapper routines
class func getToday() -> Date { return Date(); }
class func getHours(_ date : Date) -> Int { return Calendar.current.component(.hour, from: date); }
class func getMinutes(_ date : Date) -> Int { return Calendar.current.component(.minute, from: date); }
... (continued for all fields, see file) ...
You can get the integer value of the current hour in one step like this:
let currentHour = NSCalendar.currentCalendar().components(.Hour, fromDate: NSDate()).hour