UIDatePicker, choosing date shows one day earlier - swift

I have a UIDatePicker, getting the date from the picker shows different date (one day earlier) from what I chose.
For example, choosing May 2, 2019, shows 2019-05-01
This is where I get the date for my variable:
#objc func datePickerValueChanged(sender: UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateTextField.text = dateFormatter.string(from: sender.date)
//Tag 9 is the startDateTextField, Tag 8 is the EndDateTextField
//We need this to know which variable should get the date choosen.
if dateTextField.tag == 9 {
startDateChoosen = sender.date
}else if dateTextField.tag == 8 {
endDateChoosen = sender.date
}
}
This is what I see on the screen:

The issue might be with the time zone that is set on your iPad/iPhone that you are using. Make sure the time zone set in the settings is of that of your current location.

Related

DateFormatter date from string returns nil when iPhone Date & Time 24-Hour Time is off [duplicate]

This question already has an answer here:
DateFormatter doesn't return date for "HH:mm:ss"
(1 answer)
Closed 2 years ago.
I am working on an app that initializes dates from strings returned from the backend. The dateString is returned using the following format: "2020-03-05T09:00:00+00:00"
The method I have to do the conversion is:
extension Date {
static func convertDate(_ dateString: String?) -> Date? {
guard let dateString = dateString else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter.date(from: dateString)
}
}
Everything was working fine until someone reported that if the user switches off "24-Hour Time" in settings the method above returns nil.
What am I doing wrong?
Thank you
You're using a very standardized timestamp format, which allows you to take advantage of the ISO8601DateFormatter.
let dateString = "2020-03-05T09:00:00+00:00"
let df = ISO8601DateFormatter()
df.formatOptions = [.withInternetDateTime]
if let date = df.date(from: dateString) {
print(date) // 2020-03-05 09:00:00 +0000
}
If a machine (like your server) is generating the timestamp then it will (should) always be in zulu time (GMT) so you don't need to do anything beyond this. You could specify a time zone but there isn't a point since the string will always zero it out for you.
df.timeZone = TimeZone(secondsFromGMT: 0)
This string represents an absolute moment in time. If you need a relative moment in time, such as the local time from the source, you'll need to identify that time zone and apply it here, which is also very straighforward.

How can I display the date in Swift 4 without including the year?

How can I just remove the year when using the DateFormatter Full Style. I would like it to display the date like this, ex:( Thursday, October 4). Excluding the year.
Currently I have:
func todaysDate() {
dateLabel.text = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.none)
}
If you want a properly localized but custom format, you need to use setLocalizedDateFormatFromTemplate.
func todaysDate() {
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("EEEEMMMMd")
dateLabel.text = df.string(from: Date())
}
EEEE gives the full weekday name. MMMM gives the full month name. d gives the day of the month.
Based on the user's locale, the resulting format will be in the correct order with appropriate punctuation added.
Also note there is no reason to use NSDate.
As a side note, I would refactor your code to be more like this:
func todaysDate() -> String {
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("EEEEMMMMd")
return df.string(from: Date())
}
And then where you are currently calling:
todaysDate()
I would do:
dateLabel.text = todaysDate()

Need simple way to compare a time string ONLY to the current dates time value

Say time string value is "7:00 AM" call it reminder time.
Now all I need to do is compare this time with the current dates time say its "9:00 AM" if reminder time is later than current time - return true else false. This is the format "h:mm a" for date formatters.
Simple right? It should be but I have burned too much time on this. I can get hour and minute values but when the AM/PM is considered it gets harder.
I just want to compare two time values and determine if the first is later or after the second one. The date is always today or current date so I only care about the time part of the date. Of course you have to convert to dates to do the comparison but current date is easy to get however date from "7:00 AM" string does not seem to work right in comparisons.
Anyone have a function to do this?
Thanks.
the approach would be lets date the Date() object from your current time object so you will get
default date + your time = 2000-01-01 00:00:00 +your time (7.00 AM or 9.00 PM)
now we will get the current time from today only, in same format. (Only time)
it will be something like 3.56 PM
now again we will convert this 3.56 PM to Date() with default date as prev. so now we will have two date time object with same Date(2000-01-01) and respective times.
2000-01-01 7:00:00 => this will your 7.00 AM with default date
2000-01-01 15:56:00 => this will be current time with default date
now we will compare two date object.
Check the fiddle Fiddle
func CompareMyTimeInString(myTime:String)->Bool
{
// create the formatter - we are expecting only "hh:mm a" format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
// default date with my time
var dt_MyTime = dateFormatter.date(from: yourTime)!
// current time in same format as string "hh:mm a"
var currentTimString = dateFormatter.string(from: Date());
print("Current Time is - "+currentTimString);
// current time with default date.
var dt_CurrentTime = dateFormatter.date(from: currentTimString)!
// now just compare two date objects :)
return dt_MyTime > dt_CurrentTime;
}
// then call it like
var yourTime = "7.00 AM"
var isDue = CompareMyTimeInString(myTime:yourTime);
print(isDue);
My solution was as follows.
private func ReminderAfterCurrentTime(reminderTimeString: String) -> Bool {
//Compare the two time strings and if reminderTimeString is later than current time string
//return true since Reminder is after current time.
//Get the current date and time
let currentDateTime = Date()
// Create calendar object
let calendar = NSCalendar.current
// Get current date hour and minute values for comparison.
let currentHourValue = Int(calendar.component(.hour, from: currentDateTime))
let currentMinuteValue = Int(calendar.component(.minute, from: currentDateTime))
//Now get a date from the time string passed in so we can get just the hours and minutes to compare
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.none
dateformatter.timeStyle = DateFormatter.Style.short
//Now get the date using formatter.
let reminderDateTime = dateformatter.date(from: reminderTimeString)
print("reminderDateTime = \(reminderDateTime)")
//Get reminder hour and minute for comparison.
let reminderHourValue = Int(calendar.component(.hour, from: reminderDateTime!))
let reminderMinuteValue = Int(calendar.component(.minute, from: reminderDateTime!))
print("currentHourValue = \(currentHourValue)")
print("currentMinuteValue = \(currentMinuteValue)")
print("reminderHourValue = \(reminderHourValue)")
print("reminderMinuteValue = \(reminderMinuteValue)")
//This works due to 24 hour clock. Thus AM/PM is already taken into account.
if currentHourValue < reminderHourValue {
return true
}
//Check for same hour then use minutes
if currentHourValue == reminderHourValue {
if currentMinuteValue < reminderMinuteValue {
return true
}
}
//Otherwise return false
return false
}

NSDate: Getting values for Tomorrow or Yesterday

I have a piece of code that basically acts in 2 parts:
Part 1: The user sets a Date with a UIDatePicker. For example, the user selects 1 day ahead from the current date. So the selected new date is 5/19/16 instead of 5/18/16.
Part 1 code
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
var dateString = "May-19-2016"
dateFormatter.dateFormat = "MMMM-dd-yyyy"
var due_date = dateFormatter.dateFromString(dateString)!
Part 2: I have created code that counts how many days are left from the selected date to the current date. In this example, somehow my code is saying its 0 days before tomorrow. Here is the code for the second part:
Second Part:
func computeDates(dueDate:NSDate)-> Int {
let currentDate = NSDate()
// Adding days to currentDate
let daysToAdd = 1
// Adding on Unit to the current instance
let calculateDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Day, value: daysToAdd, toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0))
// Figure out many days from may 3rd
let cal = NSCalendar.currentCalendar()
let unit = NSCalendarUnit.Day
let components = cal.components(unit, fromDate: currentDate, toDate: dueDate, options: [])
let countLeft = components.day
return countLeft
}
print("Days left: \(computeDates(due_date)) ")
// Tests
let calc_date = computeDates(due_date)
if calc_date <= -1 {
print("Yesterday")
} else if calc_date == 0 {
print("Today")
} else if calc_date > 1 {
print("Tomorrow")
}
In the part 1 example, I used a static date which I use to test this code. In this part, I set May 19, 2016, one day ahead. In the second part below in the if statement, It somehow says I have 0 days left and from what i am trying to do, it's suppose to say 1 day left before tomorrow the 19th.
Another example, If i change the 19th to the 20th, I want it to say "In 2 days" from now.
Now if I revert the day to lets say, the 15th of may (in the past), Then the if statement would say something like Overdue or the past.
How can I solve this?
It would help if you thought of NSDate as a structure that operates with the number of seconds from 2001. It means if you pick a "date", it contains "date and time". All you need to do to calculate the correct number of days between specific "dates" is to truncate a time component.
But if you only need to check whether the provided date is Yesterday, Today, or Tomorrow, NSCalendar has methods for this purpose:
Objective-C:
- (BOOL)isDateInToday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
- (BOOL)isDateInYesterday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
- (BOOL)isDateInTomorrow:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
And Swift:
#available(OSX 10.9, *)
public func isDateInYesterday(date: NSDate) -> Bool
#available(OSX 10.9, *)
public func isDateInTomorrow(date: NSDate) -> Bool
#available(OSX 10.9, *)
public func isDateInWeekend(date: NSDate) -> Bool

add a new row in tableView every single month

i have a date say 2 March 2016 stored as NSUserDefaults and i want to add a new row in TableView every time a new Month is about to come , so what should i do for accomplishing this , IMO comparing the stored Date and Current Date and if
in Curent Date a new Month is about to come in next 7 days then add the
row into table but i don't know where to start, anyone can give me some hint for checking current date's next 7 days for if a new months is about to come
and if my approach is not good enough then please correct me it'll be so appreciated by me and helpful for me
please see example for better understanding :
storedDate = 2 March 2016
currentDate = 26 March 2016
if CurrentDate + 1 Week == newMonth {
//add the Row into TableView
}
You can add an Extension to NSDate and then do all sorts of day/month addition
This method you can use to add 7 days to the current date...
func dateByAddingDays(daysToAdd: Int)-> NSDate {
let dateComponents = NSDateComponents()
dateComponents.day = daysToAdd
let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: .MatchFirst)
return newDate!
}
This method to add months to current date
func dateByAddingMonths(monthsToAdd: Int)-> NSDate {
let dateComponents = NSDateComponents()
dateComponents.month = monthsToAdd
let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: .MatchFirst)
return newDate!
}
Then you need to check that date you created and see if it its a different month than the one that is stored..
func compareMonths(newDate:NSDate)-> Bool {
let today = NSDate()
let todayPlusSeven = today.dateByAddingDays(7)
return todayPlusSeven.isNextMonth(storedDate)
}
Using this method to check if the months of 2 dates are the same
func isNextMonth(storedDate: NSDate)-> Bool {
return isSameMonthAsDate(storedDate.dateByAddingMonth(1))
}
func isSameMonthAsDate(compareDate: NSDate)-> Bool {
let comp1 = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: self)
let comp2 = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: compareDate)
return ((comp1.month == comp2.month) && (comp1.year == comp2.year))
}
An oldie but still goodie, is this page of Date helpers from Erica Sadun's github page here They are all in Obj-c but can be converted to swift easily enough. I still reference it when i need help doing date math