How to store a date from server in UTC format in realm DB (date from server is also in UTC) - ios

The date from server is 2017-12-04T16:30:00+00:00
the date which i converted using format "dd/MM/yyyy hh:mm:ss a" is 04/12/2017 04:40:00 PM.

You can use this. I use it as an extension. You can just modify the format as you want it.
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale.current
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return formatter
}()}

Related

DateFormater error only when running on iOS 13

I have a function to convert string to date format. This function works as expected on iOS 12 but on iOS 13. I get this error:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
Here is my code:
func ConvertDateAndTimeFormat2() {
let timeDate = "2019-09-24 15:00:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00")
var dateObj:Date!
dateObj = dateFormatter.date(from: timeDate)
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00")
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz"
timeFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00")
var timeObj:Date!
timeObj = timeFormatter.date(from: timeDate)
timeFormatter.dateFormat = "HH:mm"
timeFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00")
let timef = "\(timeFormatter.string(from: timeObj!))"
let Date = "\(dateFormatter.string(from: dateObj!))"
}
Please change your dateformat and use "yyyy-MM-dd HH:mm:ss Z" and try.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
For more details please visit https://nsdateformatter.com/
If you are trying to convert string time which in 24 hours format (Ex 15:25:00 / HH:mm:ss) then enable your device 24-Hour Time option. It might solve the issue in IOS 13.3
You may find the option here
Settings -> General -> Date & Time
There are many issues with your code. There is no reason to create two Date objects from one string. Just parse the original string once. Then you can create your date string and time string with the desired formats from that one date.
You should also use the special locale of en_US_POSIX when parsing fixed format date strings. There is also no need to set a timezone when parsing the original date string. The string provides its own timezone. The +0000 means it is UTC time.
You may not want to provide a timezone when converting the date to your final strings either. Most likely you want strings in the user's locale timezone, not some hardcoded timezone.
Here's your code cleaned up a lot:
func convertDateAndTimeFormat2() {
let timeDate = "2019-09-24 15:00:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
if let dateObj = dateFormatter.date(from: timeDate) {
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00") // Probably not needed
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
timeFormatter.timeZone = TimeZone(abbreviation: "GMT+3:00") // Probably not needed
let timef = timeFormatter.string(from: dateObj)
let datef = dateFormatter.string(from: dateObj)
print("Date: \(datef), time: \(timef)")
}
}
convertDateAndTimeFormat2()
Output:
Date: Tuesday, Sep 24, 2019, time: 18:00

what is the format I should use for the ISO timestamp in my case

I have a ISO 8061 format timestamp string "2018-06-13T12:11:13+05:00", what is the correct way to create Date object out from the String?
I tried:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let myDate = formatter.date(from: "2018-06-13T12:11:13+05:00")
But it doesn't work correctly, myDate is one hour behind. What is the format string I should use for this kind of timestamp?
For ISO 8601 time zone format
use ZZZZZ in capital
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
EDIT
Check the following example
I have just changed +05:30 from 05:00
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
formatter.timeZone = TimeZone(identifier: "UTC")
let myDate = formatter.date(from: "2018-06-13T12:11:13+05:30")
formatter.dateFormat = "yyyy-MM-dd HH:mm"
formatter.timeZone = TimeZone.current
print(formatter.string(from: myDate!))
Output
2018-06-13 12:11

How to extract today, yesterday from Date() and make it localised like weekday and months?

I want to extract today, yesterday from date so it is localised automatically when I change language like which happens with weekdays and month.
Code for localised date that I am using:
let dateFormatter = Foundation.DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let dateStr = dateFormatter.string(from: datePickerView.date)
let timeStr = "00:00:00.000"
let dateString = NSString(format:"%# %#",dateStr,timeStr)
let mainDF = Foundation.DateFormatter()
mainDF.dateFormat = "MMMM dd, yyyy hh:mm:ss.SSS"
mainDF.locale = Locale(identifier: "en_US_POSIX")
mainDF.timeZone = TimeZone(identifier: "UTC")
let date = mainDF.date(from: dateString as String)
How to achieve this?
DateFormatter has special flag for that: doesRelativeDateFormatting, which renders dates in relative format, using locale set for this formatter.
… If a date formatter uses relative date formatting, where possible it
replaces the date component of its output with a phrase—such as
“today” or “tomorrow”—that indicates a relative date. The available
phrases depend on the locale for the date formatter; whereas, for
dates in the future, English may only allow “tomorrow,” French may
allow “the day after the day after tomorrow,” …
Example:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent // Using system locale
dateFormatter.doesRelativeDateFormatting = true // Enabling relative date formatting
// other dataFormatter settings here, irrelevant for example
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
let now = Date()
let dateString: String = dateFormatter.string(from: now)
print("dateString: \(dateString)") // Prints `dateString: <Today in current locale>`

How to change the timeZone in SwiftDate?

I have displayed the list of timezones in my app. If user selects a particular timezones, I need to change the local timezone to the selected timezone by the user.
let region = Region(tz: timeZoneName.timeZone , cal: cal, loc: cal.locale!)
let date = Date().inRegion(region: region).absoluteDate
Here is the problem, the region is changed to the selected timezone but the date issuing the local timezone.
A Date contains no timezone. From apple's docs: A specific point in time, independent of any calendar or time zone.
The timezone comes into play as soon as you want to present a date to the user. And that's what a DateFormatter is for. As #AlexWoe89 already pointed out, it let's you convert a string, containing a date into a Date object, but also lets you convert a given date into a string representing the date in the time zone you set to the timeZone property of DateFormatter.
let date = Date()
var dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
dateFormatter.timeZone = TimeZone(identifier: "America/Los_Angeles")
let dateString1 = dateFormatter.string(from: date)
dateFormatter.timeZone = TimeZone(identifier: "Germany/Berlin")
let dateString2 = dateFormatter.string(from: date)
This will store 2017-10-23 04:27 in dateString1, while the same date leads to 2017-10-23 13:27 in dateString2.
You can use DateFormatter as a solution, try something like this:
let dateString = "<yourDateAsString>"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // => there are a lot of identifiers you can use
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.defaultDate = Date()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm” // => your needed time format
let convertedDate = dateFormatter.date(from: dateString)

swift NSDate AM and Pm Format [duplicate]

This question already has answers here:
NSDateFormatter- stringFromDate not returning AM/PM
(6 answers)
Closed 5 years ago.
To convert date and time, I have used this:
let formatter = NSDateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = "M/dd/yyyy, h:mm"
formatter.AMSymbol = "AM"
formatter.PMSymbol = "PM"
let dateString = formatter.stringFromDate(model.courseDate)
print(dateString)
If the course date is "courseDate = "2017-01-09 01:00:00 +0000";"
but I am getting like this in print:
1/09/2017, 1:00 with no any AM or PM.
How can I achieve this?
Thanks.
according to the date formatter specs
You can retrieve a date in 24h format instead of requesting AM/PM by using
HH instead of hh
so the date "21/11/2016 01:30" (pm) would be "21/11/2016 13:30".
if you do need to print the format, though, you can print it using:
a
More date fomatting details here
As per Apple general date formatter you should use "M/dd/yyyy, hh:mm a" in your date format.
like : formatter.dateFormat = "M/dd/yyyy, hh:mm a"
Hope this will help you!
use following code may help full for you
//Call function
let dateTime = self.convertDateFormaterAamer(sendTimeStep, inputDateFormate: "dd-MM-yyyy HH:mm:ss", outputDateFormate: "dd-MMM-yyyy hh:mm a")
//Date function
func convertDateFormater(date: String,inputDateFormate: String , outputDateFormate: String) -> String
{
let dateFormatter = NSDateFormatter()
//dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
//dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = inputDateFormate
let date = dateFormatter.dateFromString(date)
//dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
//dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = outputDateFormate
var timeStamp = ""
if (date != nil)
{
timeStamp = dateFormatter.stringFromDate(date!)
}
return timeStamp
}

Resources