Convert string with timezone to date - swift

I have this type of string and want to convert it to date
"2017-05-27T00:00:00.000+0400"
but none of this formatters convert it to date
"yyyy-MM-dd'T'HH:mm:SSSZ"
"yyyy-MM-dd'T'HH:mm:SSSX"

Your forgot to add ss for seconds so correct formate should be yyyy-MM-dd'T'HH:mm:ss.SSSZ
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2017-05-27T00:00:00.000+0400")

Your error was that the seconds were missing. So the right format should be: yyyy-MM-dd'T'HH:mm:ss.SSSZ. You can also use an extension for this purpose:
extension String {
var toCustomDate: Date {
return Date.Formatter.customDate.date(from: self)!
}
}
extension Date {
struct Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return formatter
}()
}
var customDate: String {
return Formatter.customDate.string(from: self)
}
}
let str = "2017-05-27T00:00:00.000+0400"
let date = str.toCustomDate
If you have more date formats, then just add them to the extensions.

you can do like this
let dateString = "2017-05-27T00:00:00.000+0400"
let formachanger = DateFormatter()
formachanger .dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let dateFromString = formachanger .date(from: dateString) {
formachanger .dateFormat = "yyyy-MM-dd HH:mm"
let stringFromDate = formachanger .string(from: dateFromString)
}

try this function
func getGMTDateFrom(String string : String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zz"
let dateObj = dateFormatter.date(from: string)
return dateObj
}
Change date format according to your need.

Related

How convert DateTime to string

I get from server response in DateTime like this :
2019-04-24T16:25:02.557Z
and I would like only in String:
2019-04-23
How can I do this?
my code:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
let k = dateFormatterPrint.string(from: date)
destinationVC.createdJob = k
} else {
print("There was an error decoding the string")
}
To convert the 2019-04-24T16:25:02.557Z to a Date object, you'd use:
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions.insert(.withFractionalSeconds)
guard let date = iso8601DateFormatter.date(from: "2019-04-24T16:25:02.557Z") else { return }
And then to output only a date string in the UI, with no time, you'd use something like:
let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .medium
let result = outputFormatter.string(from: date)
What about this ?
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
Try,
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
let d = "2019-04-24T16:25:02.557Z"
if let date = dateFormatter.date(from: d) {
let k = dateFormatterPrint.string(from: date)
print(k)
} else {
print("There was an error decoding the string")
}
Your dateFormatter.dateFormat should be yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and your dateFormatterPrint.dateFormat should be yyyy-MM-dd.

How to convert this string in a date with this format?

Im working with a API, when I ask for a date, this API get my a String like this:
20190717-0300
I want to show that date in a UILabel with this format: "dd '\(preposition)' MMMM"
My attempt was to make a string extension:
extension String {
var toDate: String? {
let dateFormatter = DateFormatter()
let preposition = NSLocalizedString("of", comment: "Preposition of dates formatted")
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
dateFormatter.locale = Locale.current
if let date = dateFormatter.date(from: self) {
let dateString = dateFormatter.string(from: date)
return dateString
}
return nil
}
}
And then use it:
myLabel.text = thatString.toDate
But .toDate always return nil
Note: The answers I found on the site are cases with ISO format strings.
Expected result:
17 of July
Basically you need an input date format and an output date format.
extension String {
var toDate: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddZ"
if let date = dateFormatter.date(from: self) {
let preposition = NSLocalizedString("of", comment: "Preposition of dates formatted")
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
let dateString = dateFormatter.string(from: date)
return dateString
}
return nil
}
}
I totally agree with rmaddy's comment to use setLocalizedDateFormatFromTemplate
The source of the date field symbols is unicode.org: Date Format Patterns
Turn this into extension if you like:
// function
func formatDate(_ from:String, preposition:String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddZ"
guard let date = dateFormatter.date(from: from) else {
return nil
}
dateFormatter.dateFormat = "dd '\(preposition)' MMMM"
return dateFormatter.string(from: date)
}
// example usage
let str = "20190717-0300"
if let formatted = formatDate(str, preposition: "of") {
print(formatted)
}

Parsing a Swift String to Date, then Components

I have a date "2017-12-31" as a String.
What I want to get finally is only the month: "12" as a String.
So I thought that I can change it to Date using a date formatter
let formatter = DateFormatter()
formatter.dateFormat = "MM"
What do I do next?
let dateString = "2017-12-31"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601) formatter.timeZone = TimeZone(identifier: TimeZone.autoupdatingCurrent.identifier)
formatter.dateFormat = "yyyy-MM-dd"
let localDate = formatter.date(from: dateString)
formatter.dateFormat = "MM"
let strMonth = formatter.string(from: localDate!)
print("Month is:",strMonth)
Another way
let dateString = "2017-12-31"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let localDate = formatter.date(from: dateString)
let month = String(NSCalendar.current.component(.month, from: localDate!))
print(month)
First you have to use the DateFormatter to create a temporary Date object from your source String object. Then you have to use it to create your final String from the temporary Date object.
let dateString = "2017-12-31"
let dateFormatter = DateFormatter()
// set the dateFormatter's dateFormat to the dateString's format
dateFormatter.dateFormat = "yyyy-MM-dd"
// create date object
guard let tempDate = dateFormatter.date(from: dateString) else {
fatalError("wrong dateFormat")
}
// set the dateFormatter's dateFormat to the output format you wish to receive
dateFormatter.dateFormat = "LL" // LL is the stand-alone month
let month = dateFormatter.string(from: tempDate)
Use below function for getting month from string file of date
func getMonthFromDateString(strDate: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: strDate) // Convert String File To Date
formatter.dateFormat = "MM"
let strMM = formatter.string(from: date!) // Convert date to string
return strMM
}

swift 4 Date from from ISO string to custom format?

I have ISO date from API I want to convert it to another custom date format, I've checked some threads here it's look like I have to use the extension on Date class, unfortunately, all my attempts failed.
this example for date i have :
2014-10-22T00:00:00+00:00
I want to convert it to July 2014
can I use normal Date class to do it?
and below what I am trying to do
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: "2016-08-26T12:39:00Z")
let string = formatter.string(from: Date())
Try it:
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: "2014-10-22T00:00:00+00:00") {
let string = date.stringDate
print(string) // October 2014
}
extension Date {
var stringDate: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: self)
}
}
my Date load from SQL Server and format like this "2018-01-17T03:08:28.158769" the code below is work for me perfectly
let isoDate = "2018-01-17T03:08:28.158769"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
let date = dateFormatter.date(from:isoDate!)!
dateFormatter.dateFormat = "d.MMMM.YYYY"
let displayDate = dateFormatter.string(from: date)
displayDateInLabel.text = displayDate
result
17.January.2018
You can get Month and Year like this
override func viewDidLoad() {
super.viewDidLoad()
print(getFormattedDate(date: Date()))
}
func getFormattedDate(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM YYYY"
let strMonth = dateFormatter.string(from: date)
return strMonth
}

Change date format in Swift

I have a date format in String value of "2015-08-27" which is "YYYY-MM-DD". I need to convert this to Date format and change the format to "DD-MMM-YYYY". And change it back to String format again to display. So the end result would be "27-AUG-2015".
I have been searching for codes, but couldn't find one.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD"
let date = dateFormatter.dateFromString("2015-08-27")
dateFormatter.dateFormat = "DD-MMM-YYYY"
let goodDate = dateFormatter.stringFromDate(date!)
Its not tested but I hope it will work.
You can create a class helper like DateHelper and class func:
class func convertDateString(dateString : String!, fromFormat sourceFormat : String!, toFormat desFormat : String!) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = sourceFormat
let date = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = desFormat
return dateFormatter.string(from: date!)
}
And use it:(note format you give on question wrong so it will wrong convert): begin format is YYYY-MM-dd and you want convert to dd-MMM-YYYY)
print(DateHelper.convertDateString("2015-08-27", fromFormat: "YYYY-MM-dd", toFormat: "dd-MMM-YYYY"))
Hope this help.
Just used the function in your code(swift 4.2).
public func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}
Thanks