How to convert date from one format to another? Need to get date to "Tue Apr 3 22:10:06 2018" format - swift

How to convert "2018-04-03 22:10:06" to "Tue Apr 3 22:10:06 2018"? Obviously not those specific dates but that format.
I found this solution:
How to convert date format from dd/MM/YYYY to YYYY-MM-dd in swift
but I am unable to get it to the exact format.

So, I just threw this into Playgrounds
let inFormat = DateFormatter()
inFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = inFormat.date(from: "2018-04-03 22:10:06")
let outFormat = DateFormatter()
outFormat.dateFormat = "E MMM d HH:mm:ss yyyy"
outFormat.string(from: date!)
It eventually outputs Tue Apr 3 22:10:06 2018
The formats were initial referenced from nsdateformatter.com
This, of course, will use the current system TimeZone and Locale, so you may want to do some more investigation into that

Related

Swift 5 - Dateformatter not working as expected [duplicate]

This question already has answers here:
Swift - Get local date and time
(11 answers)
Closed 1 year ago.
I was playing around with date formatter in swift, but the AM/PM thing is not working in my code.
import Foundation
let dtstr = "Tuesday, July 28, 2020 4:15:45 PM"
let formatter = DateFormatter()
formatter.dateFormat = "eeee, MMMM d, yyyy h:m:s a"
let date = formatter.date(from: dtstr)
print(date)
the output is this: Optional(2020-07-28 08:15:45 +0000). However, it should be 16:15:45 instead of this. Any idea why?
Thanks!
Date has no information about time zone, and default string representation is using a greenwich one. You can see it +0000 part in your string.
You can get description for your own time zone like this:
date.description(with: .current)

DateFormatter giving me incorrect result while I am converting String into Date in UK region and Timezone is Muscat

I want "yyyy-MM-dd HH:mm:ss", with time in 24 hour format, but as i m having 12 hrs date format setting in my phone and Timezone is set to the Muscat ,the date which I am getting is always 12 hrs format, while i m checking with UK region. I am able to change Date() into string in 24 hrs format but while I am changing 24 hrs string into 24 hrs Date , It always give me 12 hrs Date format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateToString = dateFormatter.string(from: Date()) //2020-04-06 15:47:16
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateFromString = dateFormatter.date(from: dateToString)
print(dateFromString) // 2020-04-06 1:47:25 pm +0000
A Date object just represents a point in time. The “should I show it in 12 hour clock or 24 hour clock” is not something that Date objects know about. This is a feature of strings generated by (or consumed by) a DateFormatter.
So, a few thoughts:
A date formatter’s dateFormat (and its locale) dictates what a string will look like when you call string(from:). (It will also dictate how to interpret a string and create a Date object when you call date(from:), but that’s not relevant here.)
So, if you’re looking for a string representation of a date using a 24 hour clock, look at the string generated by the date formatter’s string(from:) method. This is the dateToString string in your example.
But, if you subsequently generate a Date object from the formatter’s date(from:) method, that resulting Date will not capture whether to use 12 vs 24 hour clock. If you print this Date object, it won’t reflect your 12/24 hour clock preference.
Bottom line, only concern yourself with am/pm vs 24-hour clock when looking at String objects generated by (or passed to) the DateFormatter. Don’t worry about the format of the output when you print a Date object, as that’s for debugging purposes only and won’t capture this am/pm vs 24-hour clock dimension.
You said:
Final statement is giving me “2020-04-09 4:23:27 am +0000” format.
If you’re seeing the +0000, that suggests that you are printing the Date object, itself. The dateFormat and locale of a DateFormatter only controls the format of the string generated by string(from:) (and how strings are parsed).
So, print the string generated by DateFormatter, not Date objects. The print of a Date object will always be in this predefined format. Within the app, if you need the output in a given format, use the String generated by DateFormatter, not Date objects.
Consider a more obvious example of the issue where the DateFormatter is used to create a string in a very different format:
let now = Date()
print(now) // 2020-04-07 11:54:58 +0000
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .long
let string = formatter.string(from: Date())
print(string) // April 7, 2020 at 4:54:58 AM PDT
if let date = formatter.date(from: string) {
print(date) // 2020-04-07 11:54:58 +0000
}
So, even though that formatter successfully converted a Date to a String, and back, that final print statement uses the same fixed format that the first print statement did, because I’m just printing a Date object. I’m not concerned that the that last print statement didn’t honor the configuration of my DateFormatter. I wouldn’t expect it to. When I print a Date, it’s always in that fixed, predefined format. I only worry about the format of the strings generated by the DateFormatter (the second print statement).
As an aside, there are secondary questions about your "yyyy-MM-dd HH:mm:ss" format. What timezone does this represent? Your local timezone? Your server’s timezone? GMT/UTC/Zulu? We often use ISO8601/RFC3339 date strings (like 2020-04-07T11:54:58Z) to remove this ambiguity. You should get your arms around your original question first, but when you have that behind you, you’ll want to take a hard look at why you’re storing it in this format, and how you want to deal with timezones correctly. But first things first.

Swift - NSDate - remove part of date

I have a date in following format 2015-02-22T20:58:16+0000
In order to convert it to NSDate I found following solution
var df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
var date = df.dateFromString(myDate)
df.dateFormat = "eee MMM dd yyyy"
var dateStr = df.stringFromDate(date!)
But I want to remove +0000 from date. I tried to remove ZZZZm but app crashes.
How can I remove extra +0000 digits ?
You ask:
How can I remove extra +0000 digits?
I'm not sure what you mean, because the resulting dateStr does have the +0000 removed.
But let's step back and consider the right way to parse a date string in the format of 2015-02-22T20:58:16+0000. You should use a locale of en_US_POSIX as described in Apple Technical Q&A 1480:
let myDate = "2015-02-22T20:58:16+0000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = dateFormatter.dateFromString(myDate)
When you then want to format that for the end user, reset the locale back to currentLocale:
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "eee MMM dd yyyy"
let dateStr = dateFormatter.stringFromDate(date!)
The dateStr then becomes:
Sun Feb 22 2015
Or, perhaps better, for better localization behavior, use dateFormatFromTemplate:
let locale = NSLocale.currentLocale()
dateFormatter.locale = locale
dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("eeeMMMdyyyy", options: 0, locale: locale)
let dateStr = dateFormatter.stringFromDate(date!)
In the US, it will appear like above, but in England it will appear as:
Sun, 22 Feb 2015
Or use one of the standard dateStyle values if that works for you. But I'd generally advise against using a hard-coded dateFormat, but rather use a format that honors the end-user's localization settings.
I wouldn't recommend removing time zone when you're parsing results. But if all you want to do is remove the string, you can do it like this:
let date = "2015-02-22T20:58:16+0000"
let display = date.substringToIndex(date.characters.indexOf("+")!)
This will give you the result of 2015-02-22T20:58:16

Swift get difference between two dates in GMT

I recently noticed strange behaviour trying to find the difference between two dates (in seconds).
I have a datestring that is in GMT time:
2016-01-07 01:09:47.289000
I want to find how many seconds since that time NOW.
But I notice that when I use NSDate() I get the time of my local time, not GMT time.
How would I go about doing this?
Use the NStimeZone class to set time zone
let date = NSDate()
var formatter = NSDateFormatter()
let gmt = NSTimeZone(abbreviation: "GMT")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = gmt
formatter.stringFromDate(date)
To compare, convert the current date from NSDate to "GMT" and then calculate the time interval between the two.

SWIFT: Convert a date with the format E, dd, MMM, y, KK:mma

I am trying to convert a date from a String to NSDate with the following code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "E, dd MMM yyyy, KK:mma"
date = dateFormatter.dateFromString(strDate)
I have also tried the following formats:
EEE, dd MMM yyyy, hh:mma
EEE, dd MMM yyyy, KK:mm
but the out put is always nil
Converted Tue, 12 Jan 2016, 7:30am to nil with the formatter E, dd MMM yyyy, KK:mma
I have also considered the follow StackOverflow posts:
String to NSDate in Swift
How can I convert string date to NSDate?
and I have been using this link as a reference for the date formats
The typical reason is that your device is not set to English language. Note that parsing strings like Tue or Jan is language specific. That means you have to make sure the formatter has a correct language set, e.g.:
dateFormatter.locale = NSLocale(localeIdentifier: "en")