Swift comparing date is not working and getting wrong time - ios

Hi I have multiple dates which I am comparing with current date. But it is not working. I have done coding but nothing is working for me. I am using comparison same like this link.
Here is what I am doing
let todayDate = Date()
let date1FromServer = //its Date from server which is 2020-02-01 09:00:00 +0000
let date2FromServer = //its Date from server which is 2020-02-02 09:00:00 +0000
let date3FromServer = //its Date from server which is 2020-02-03 09:00:00 +0000
now here I am comparing All three date in simple if else
if(date1FromServer < todayDate){
//Do something for date 1
}else if (date2FromServer < todayDate){
//Do something for date 3
}else if (date3FromServer < todayDate){
// Do something for date 3
}
Case: Now I have date1 and Date 2 is working but date3 is not working. I am saying this because the date3 is exactly on 3 feb 2020
with 9:00 am which is smaller then today date which is 3 feb 2020 with
11:00 am , but it looks like that it is dealing like date 3 is equal
or greater then today date.
When I print date 3 it prints (2020-02-03 06:32:22 +0000) and here the time is wrong, as right now on my device it si 11:32 am but it showing 06: 32 . I think as I am just printing it in log so there could be problem of time zone, but on above code it is also not working.
Please let me know what is the problem here.
Note: I want to compare the Date and time as well.....

If your server date has GMT as time zone then you can adjust your local date to GMT by using offsets
let offsetDate = Date(timeIntervalSince1970:
todayDate.timeIntervalSince1970 + Double(TimeZone.current.secondsFromGMT(for: todayDate)))
and then use offsetDate instead when doing the comparison

Related

FSCalendar select day selects previous day at 23:00

I'm using FSCalendar in a Swift app, and when user selects a day, I'm printing the selected day, and the it prints the previous day, at 23:00. I'm not sure why and how can I solve this. I'm in spain. Maybe it's related with where you are and your local hour?
This is how I'm printing the selected day:
extension CalendarDataViewViewController: FSCalendarDataSource {
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss"
let now = df.string(from: date)
logger.debug("Date: \(date)")
}
}
And this is what it's printed when I select 18 march:
21:01:24.646 💚 DEBUG CalendarDataViewViewController.calendar():258 - Date: 2021-03-17 23:00:00 +0000
Your code creates a date formatter, converts the returned date to a date string with that formatter, and then ignores that and simply prints the date, which is being displayed in UTC. (Note the output Date: 2021-03-17 23:00:00 +0000)
Change your log command to read:
logger.debug("Date: \(now)")
And by the way, the variable name now is a terrible choice for holding a user-selected date that is not the current date.
I'd suggest renaming the returned date parameter selectedDate and the String output of the formatter as selectedDateString
Edit:
Consider this code:
import Foundation
func dateStringFromDate(_ inputDate: Date) -> String {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss a"
let dateString = df.string(from: inputDate)
return dateString
}
func isoDateStringFromDate(_ inputDate: Date) -> String {
let df = ISO8601DateFormatter()
df.formatOptions = .withInternetDateTime
df.timeZone = TimeZone.current //Force the formatter to express the time in the current time zone, including offset
let dateString = df.string(from: inputDate)
return dateString
}
let now = Date()
print("Current timezone = \(TimeZone.current)")
print("now in 'raw' format = \(now)")
let localizedDateString = DateFormatter.localizedString(from: now,
dateStyle: .medium,
timeStyle: .medium)
print("localizedString for the current date = \(localizedDateString)")
print("dateStringFromDate = \(dateStringFromDate(now))")
print("isoDateStringFromDate = \(isoDateStringFromDate(now))")
Right now, at about 9:16 PM EDT on Thursday March 18th, that logs the following:
Current timezone = America/New_York (current)
now in 'raw' format = 2021-03-19 01:16:52 +0000
localizedString for the current date = Mar 18, 2021 at 9:16:52 PM
dateStringFromDate = 2021-03-18 09:16:52 PM
isoDateStringFromDate = 2021-03-18T21:16:52-04:00
The 'raw' date format is in GMT, with an offset value of 0. In that form, in GMT, the calendar date is already March 19th. (Because GMT is 4 hours ahead of EDT)
The class function NSDateFormatter.localizedString(from:dateStyle:timeStyle) displays a date in the current time zone and using the device's locale settings. The dateStyle and timeStyle parameters give you the option to choose whether or not, and in what format (short, medium, or long) to display the date or time.
An ISO8601DateFormatter displays the date following the conventions in the ISO8601 standard. The isoDateStringFromDate(:) function above uses the .withInternetDateTime option to express the date in the ISO8601 "internet date and time" format. I forced that date to be in the local time zone, so it displays the date with a -4 hour offset from GMT (since it is EDT, eastern daylight savings time where I live.)
The function dateStringFromDate(_:) is a slight variation on your function. It returns a date string in the current time zone, using 12 hour times and an AM/PM string.

Converting 12 digit ticks to Date

I am trying to convert 12 digit c# date time ticks formatted time. (648000000000). With the help of following link I added an extension to my code How to get 18-digit current timestamp in Swift?.
extension Date {
init(ticks: UInt64) {
self.init(timeIntervalSince1970: Double(ticks)/10_000_000 - 62_135_596_800)
}
}
let date = Date(ticks: 648000000000)
When I try to see result date it prints following;
0001-01-03 18:00:00 +0000
However, when I try to convert it hour and minute format output is irrelevant like 19:55
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.string(from: date)
My first question is how can I format it to get only 18:00. Second is why it is printing 18:00 when I print only date, but 19:55 when I format it?
Just don't subtract 62_135_596_800
extension Date {
init(ticks: UInt64) {
self.init(timeIntervalSince1970: Double(ticks)/10_000_000)
}
}
1970-01-01 18:00:00 +0000
The other problem: When you create date and print it, the string is formatted in UTC time zone (offset GMT+0). But DateFormatter returns string representation dependent on its time zone, which is the local timezone by default.
You can fix your code just by setting dateFormatter's timeZone to UTC
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
18:00
Apparently your timestamp represents a duration as the number of 100-nanosecond ticks, not a date. If you divide the number by 10^7 then you get the number of seconds. These can be printed as a duration with a DateComponentsFormatter.
Example:
let ticks = 648000000000
let seconds = TimeInterval(ticks) / 10_000_000
let fmt = DateComponentsFormatter()
fmt.allowedUnits = [.hour, .minute]
print(fmt.string(from: seconds)!)
18:00
The duration is 64800 = 18 * 60 * 60 seconds, that are exactly 18 hours.

Firebase & Swift - Date saved with UTC -7?

I'm trying to understand how exactly dates are saved in the CloudFirestore of Firebase...
When I put the current date in the database dateToSAve = Date() , this date is stored with UTC-7:
But in someone in France for example, want to save data on Firebase, it will be the current date -9 hours to conform with the UTC -7
And sometimes, because of that, it can be a different day...
Do you know how to handle this problem? I would like to save in the database, the current date of the user.
You should not store date object in database, instead you should save timestamp in UTC 0. And after retrieving that timestamp you can convert it back into date with the time portion in your current time zone.
For getting timestamp in UTC 0:
let timestamp = Date().timeIntervalSince1970
And for converting timestamp back to date with the time portion in your current timezone:
// gives date with time portion in UTC 0
let date = Date(timeIntervalSince1970: timestamp)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM-dd-yyyy" // change to your required format
dateFormatter.timeZone = TimeZone.current
// date with time portion in your specified timezone
print(dateFormatter.string(from: date))

Get UTC Date To Local Date in swift iOS

I am trying to convert UTC Date to local date in swift but after get UTC To Local date in string i convert that string to again in NSDate but i am always getting in UTC date format, below is my code
Date : in UTC : 2016-07-20 18:30:00 +0000
I am trying this date in local date, check below code:
let dateInUTC = NSDate()
let seconds: Int = NSTimeZone.systemTimeZone().secondsFromGMT
print(seconds)
let localDateFormatter: NSDateFormatter = NSDateFormatter()
localDateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
localDateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: seconds)
let lastDate: String = localDateFormatter.stringFromDate(dateInUTC)
print(lastDate)
at this time i am getting “07/12/2016 16:56:36 GMT+5:30”, means i got local date in string but i want this date in NSDate so again i convert this string date in NSDate,check below
let getDate:NSDate = localDateFormatter.dateFromString(lastDate)!
print(getDate)
but at this stage again i got date in UTC (2016-07-12 11:26:36 +0000) but i want in local date,
I tried a lot of times in Swift but not getting local date from string,this line of code i used in objective-c, its working fine in obj-c but when i am trying in swift i always get UTC date,suggest me and give me right way to sol this.
NSDates don't save time zone information. You always have to use the dateFormatter with time zone when retrieving.

NSDateformatter does not provide correct date swift

When I am using NSDateformatter to get date from string it returns wrong value.I dont know what must be reason.Please help me to resolve.
Thanks in advance.
Input String:-
newDate "06:11"
end time "07:00"
start time "05:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date:NSDate = dateFormatter.dateFromString(dateString)!
println(date)
Output Date:-
current date 2000-01-01 00:41:00 +0000
end date 2000-01-01 01:30:00 +0000
start date 1999-12-31 23:30:00 +0000
By doing
println(date)
You are printing the description of the date, which is equal to -
println(date.description())
And it always prints the time in UTC (GMT)
So if you are in UTC+5:30, it will display time that is before 5:30 hours than your entered time. If you want to print date in your timezone, use a NSDateFormatter again. To see date of other time zone, set NSDateFormatter timeZone.
Hope this explains.

Resources