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
Related
Comparison is required to check date is past date day.
I have tried with this
let calendar = NSCalendar.current
//Get just MM/dd/yyyy from current date
let components = calendar.dateComponents([], from: Date())
//Convert to NSDate
let pastDates = self.calendar.selectedDates.filter { $0 < calendar.date(from: components as DateComponents)! }
Update the below line to give you a date object,
let components = calendar.dateComponents([.month, .day, .year], from: Date())
Currently you are not providing any date component in the array so you will not get a date object.
I didn't understood what is your question properly, but hope this helps you:
let beforeDateStr = "04/12/2018"
let todayDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let beforeDateFormatted = dateFormatter.date(from: beforeDateStr)
if Calendar.current.compare(todayDate, to: beforeDateFormatted!, toGranularity: .day) == .orderedDescending {
print("before date day is lesser than current date")
} else {
print("before date day is equal or greater than todays date")
}
To find the date is smaller or bigger:
You can use this simple Code:
let differenceBetweenTwoDate = Calendar.current.dateComponents([.day], from: previousDate, to: Date())
if differenceBetweenTwoDate.day! > 0{
print("date is bigger")
}else{
print("date is smaller")
}
Hope it Helps!
This is how you can add hours or days in current date and time -
calendar.date(byAdding: .hour, value: 1, to: currentDate)
calendar.date(byAdding: .day, value: 7, to: currentDate)
And this is how you can compare 2 dates and calculate hours, mins and also days
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let anyDataTime = dateFormatter.date(from: anotherDateTime)
let components = calendar.dateComponents([.minute], from: Date(), to: anyDataTime!)
let hour = (Double(components.minute!) / 60.0).rounded()
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)
Goord Morning all together,
i have an app with ios 8 and swift.
in there is a UIViewcontroller within a UIDatepicker
I set a minimum date. for example the date of today: 2 | May | 2015
with this solution it should not be possible to set a date which is in the past
but if would like to set this date 15 | January | 2016
i set at first the day to 15
than the month to january but then the UIDatepicker goes back to the minimum date 2 May 2015
is it be possible, that wenn change the day to 15 and the month to january, that the year changes automaticly to 2016?
Let your minimumDate unset and try to configure it by code...
Try this:
#IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = NSDate()
let nowCalendar = NSCalendar.currentCalendar()
let nowComponents = nowCalendar.components([.Day, .Month, .Year], fromDate: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compareDate(sender.date, toDate: now, toUnitGranularity: [.Day, .Month, .Year]) == NSComparisonResult.OrderedAscending
{
let dateCalendar = NSCalendar.currentCalendar()
let dateComponents = dateCalendar.components([.Day, .Month, .Year], fromDate: sender.date)
dateComponents.year = nowComponents.year + 1
let newDate = dateCalendar.dateFromComponents(dateComponents)
sender.date = newDate!
}
}
///Swift4 Version - I think it may works with 3 too.
#IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = Date()
let nowCalendar = Calendar.current
let nowComponents = nowCalendar.dateComponents([.day, .month, .year], from: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compare(sender.date, to: now, toGranularity: Calendar.Component.day) == ComparisonResult.orderedAscending
{
var dateCalendar = Calendar.current
var dateComponents = dateCalendar.dateComponents([.day, .month, .year], from: sender.date)
guard let year = nowComponents.year else { return }
dateComponents.year = year + 1
let newDate = dateCalendar.date(from:dateComponents)
sender.date = newDate!
}
}
I published a complete example working in playground if you wish to play a little.
https://gist.github.com/dedeexe/4878f78d7e1d5fe8b372ef84de629b59
For swift 4:
I have like this.
1. My function:
func AddDaysToToday(days: Int) -> Date? {
var dateComponents = DateComponents()
dateComponents.day = days
return Func.GetCalendar(tz: .utc).date(byAdding: dateComponents, to: Date()) //you can return your own Date here.
}
In my VC:
let today = DateFunc.AddDaysToToday(days: 0)
datePicker.minimumDate = today
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)