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()
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!)
Lets say i have a program that reminds users of their appointments , from the current date until the date of the appointment, i want to find out if a particular date is a week to the appointment or a month to the appointment .
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
var newDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
if newDate is a month to endDate {
//schedule reminder
}
if newDate is a week to endDate{
//schedule reminder
}
how can i check if the current date is a week/month to the appointment ?
You don't need to use any date comparison, you can simply generate the notification dates using Calendar.date(byAdding:value:to:) and just passing the correct components. To set the date 1 week/month before endDate, pass -1 to value.
let oneWeekBeforeAppointment = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: endDate)!
let oneMonthBeforeAppointment = Calendar.current.date(byAdding: .month, value: -1, to: endDate)!
Try this to calculate the duration in days
func DateFormat() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
return dateFormatter
}
var appointementDate: Date?
var today = Date()
appointementDate = DateFormat().date(from: "22/02/2020")
today = DateFormat().date(from: DateFormat().string(from: today))!
let timeInterval = Int(exactly: (today.timeIntervalSince(appointementDate!))) ?? 0
print("\(timeInterval/86400) days left")
Here is my first question;
import Foundation
let date1 = Date()
let date2 = Date().addingTimeInterval(3600)
if date1 == date2
{
print("equals")
}
else if date1 > date2
{
print("date1 is bigger")
}
else if date1 < date2
{
print("date2 is bigger")
}
It gives below output if i write print("date1") or print("date2")
2018-09-10 08:56:49 +0000
I would like to write the same example but date1 and date2 must include these 2 properties:
format: "dd.MM.yyyy"
locale: "tr_TR"
Beside this, here is my second question:
let date2 = Date().addingTimeInterval(3600)
As you know, this 3600 value adding an hour. How can I add one day? 24*3600? Is there any shortest way?
Try
extension Date {
func addDays(_ days: Int) -> Date {
Calendar.autoupdatingCurrent.date(byAdding: .day, value: days, to: self)!
}
}
Like #Larme said, you might want to look into Calendar.
var dateComponents = DateComponents()
dateComponents.day = 1
guard let date = Calendar.current.date(byAdding: dateComponents, to: Date()) else { // Adding date components to current day.
fatalError("date not found")
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short // dd.MM.yyyy
dateFormatter.locale = Locale(identifier: "tr_TR") // Your preferred locale
let dateWithLocale = dateFormatter.string(from: date)
print(date)
Your comparison can be done using the Date objects. Only when you need to print it or use it as a String, you would need to do formatting.
Try this one
let today = Date() // OR your date here
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
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"
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