How convert DateTime to string - swift

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.

Related

DateFormater gives day before swift

when I use DateFormateer it returns me a day before.
nextDayShouldBe = currectDay.addingTimeInterval(24 * 3600)
print(nextDayShouldBe) //prints (2022-07-02 21:58:11 +0000) it's right
let nextDay = nextDayShouldBe?.getFormattedDate(format: format)
try? realm.write({
userData?.nextDay = nextDay
print(nextDayShouldBe?.getFormattedDate(format: format)) // prints "01/07/2022"
})
I tried all methods to fix it (dateformatter.locale, timeZone, calendar).
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
dateformat.timeZone = TimeZone(secondsFromGMT: 10800)
dateformat.calendar = .current
dateformat.locale = Locale.autoupdatingCurrent
return dateformat.string(from: self)
}
}
How to get 2022-07-02 ??
okey, I did it and it works:
nextDayShouldBe = currectDay.addingTimeInterval(24 * 3600)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let fromDateToString = dateFormatter.string(from: nextDayShouldBe!)
print(fromDateToString)

SwiftUI string to formatted date (ISO)

can you please help me with that topic?
from the API i get the following date as a string: 2021-05-21T14:35:15.647+02:00
How can i convert this to a date object, so that i can format it?
I tried it in different ways as subscribed here in stackoverflow or in other tutorials, like this:
let date = "2021-05-21T14:35:15.647+02:00"
func formatStringDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let newDate = dateFormatter.date(from: date)
dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d, yyyy")
return dateFormatter.string(from: newDate!)
}
var newDate = formatStringDate(date: date)
print(newDate)
or
let timestampString = "2018-12-09T11:08:48-05:00"
if let date = isoDateFormatter.date(from: timestampString) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM, dd, yyyy h:mm a"
let dateFormattedString = dateFormatter.string(from: date)
print(dateFormattedString) // December, 09, 2018 11:08 AM
} else {
print("not a valid date")
}
But it´s not working.
Thanks for your help
Thanks for your help, i got the following snippet to work:
let dateString = "2021-05-21T14:35:15.647+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate
]
let date = inputFormatter.date(from: dateString)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YYYY"
print(dateFormatter.string(from: date!))
Thanks

getting nil value after converting it to the required Date.Function returning nil values

In the below function Given ,I am getting nil value while converting it to the required date.
func convertdate(input:String) -> String
{
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "d MMM,yyyy"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: input)
formatter.dateFormat = "EEE d MMM yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
return updatedString
}
calling function like this convertdate(input:"23 Jul,2020")
You have to set the locale to a fixed value and you should return nil if the string cannot be converted.
func convertdate(input:String) -> String?
{
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "d MMM,yyyy"
guard let yourDate = formatter.date(from: input) else { return nil }
formatter.dateFormat = "EEE d MMM yyyy"
let updatedString = formatter.string(from: yourDate)
print(updatedString)
return updatedString
}
I removed the variable myString because it's unused.

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
}

Convert string with timezone to date

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.