Not able to get date in string format - ios

I'm storing some dates in coredata in Date format. In another viewcontroller, I want to retrieve those dates and convert them to string. I tried to achieve it like so...
if let bday = result.birthday {
print(bday)
let formatter = DateFormatter()
let bDateString = formatter.string(from: bday as Date)
print(bDateString)
self.birthdate = bDateString
}
Here, printing bday gives the proper date. But printing bDateString after converting to string gives nil. What am I doing wrong...?

Please provide format of date like this :
formatter.dateFormat = "MM-dd-yyyy" //provide your date format here

The issue is you have not provided date format.
Even you can use this extension
extension Date { static func getFormattedDate(string: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // This formate is input formated .
let formateDate = dateFormatter.date(from:"2018-02-02 06:50:16 +0000")!
dateFormatter.dateFormat = "dd-MM-yyyy" // Output Formated
print ("Print :\(dateFormatter.string(from: formateDate))")//Print :02-02-2018
return dateFormatter.string(from: formateDate)
} }

Related

Convert Date from one format to another

I trying to convert date from one format to another. But the date in the below code is coming as nil. Can you guys help me out below is the code.
func eventTimeDate() -> Date {
let dtf = DateFormatter()
dtf.timeZone = TimeZone.current
dtf.dateFormat = "yyyy-MM-dd HH:mm:ss z"
/// "2020-05-28 00:20:00 GMT+5:30"
let stringDate = dtf.string(from: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss z"
/// nil
let date = dateFormatter.date(from: stringDate)
return date!
}
If you need to convert from one formatted date string to another formatted date string, you can use two DateFormatters: one - an input formatter to convert a String to an intermediary Date object, and then - using an output formatter - convert from Date to String.
func reFormat(from dateStr: String) -> String? {
let fromFormatter = DateFormatter()
fromFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
let toFormatter = DateFormatter()
toFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss z"
guard let date = fromFormatter.date(from: dateStr) else { return nil }
return toFormatter.string(from: date)
}
If you just need to return a Date object, then it's a simpler function using just one DateFormatter:
func toDate(from dateStr: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
return formatter.date(from: dateStr)
}
Date object itself has no formatting - it's a pure representation of a date & time, which you can convert to/from using different formatters.
A swift class Date has no format.
In your code your stringDate is in "yyyy-MM-dd HH:mm:ss z" format. If you need to convert String to Date you must use the same format otherwise it will return nil.
If you want to change a format of a string then first convert it to a Swift 'Date' then again convert it to a string with the use of new Formatter.
func eventTimeDate(dateString : String, currentFormat : String, newFormat : String) -> String? {
let currentDateFormatter = DateFormatter()
currentDateFormatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
currentDateFormatter.locale = Locale(identifier: "en_IN")
currentDateFormatter.dateFormat = currentFormat
let date = currentDateFormatter.date(from: dateString)
let newDateFormatter = DateFormatter()
newDateFormatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
newDateFormatter.locale = Locale(identifier: "en_IN")
newDateFormatter.dateFormat = newFormat
if let date = date {
let newDateString = newDateFormatter.string(from: date)
return newDateString
}
return nil
}
You have three problems in your code. First when parsing a fixed date format you should always set the date formatter's locale to "en_US_POSIX". Second you need to escape the GMT of your date string. Last but not least important you need to fix your timezone string which it is missing the leading zero for your timezone hour:
let dateStr = "2020-05-28 00:20:00 GMT+5:30"
let formatter = DateFormatter()
// set the date formatter's locale to "en_US_POSIX"
formatter.locale = .init(identifier: "en_US_POSIX")
// escape the GMT of your date string
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'GMT'Z"
// add the leading zero for your timezone hour
let string = dateStr.replacingOccurrences(of: "(GMT[+-])(\\d:)", with: "$10$2", options: .regularExpression)
if let date = formatter.date(from: string) {
print(date) // "2020-05-27 18:50:00 +0000\n"
}

How to convert a sting to a date, and back again, in swift?

I receive a timestamp from a JSON request, and I want to format it to a user-friendly format. Both the input, as the desired output are of type 'String'.
The format of the input timestamp is: 2020-03-07T12:18:26.347Z
Using the following code, I try to convert it to the desired format. But it will just output the value of Date(), indicating that the output of formatter.date(from: date) is nil.
What am I missing?
func convertDate(date: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "d-M-y, HH:mm"
let convertedDate = formatter.date(from: date) ?? Date()
return formatter.string(from: convertedDate)
}
Your dateFormat doesn't match the format of your input string. You want something like:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
After struggling with it for hours, this answer, together with the date format information found here, I figured it out. I did previously not describe to the dateformatter how the input string would look.
func convertDate(date: String) -> String {
let dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
//`date(from:)` returns an optional so make sure you unwrap when using.
let dateFromString: Date? = dateFormatter.date(from: date)
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy, HH:mm"
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString!)
return stringDate
}

Swift how to convert date format [duplicate]

This question already has answers here:
Date Format in Swift
(24 answers)
Closed 2 years ago.
I have a date of type date and has a format "yyyy-MM-dd HH:mm:ss" and I would like to convert it to "yyyy-MM-dd". I am not sure how to achieve this since the date is of type Date.
Example :
let dateComponents: Date? = dateFormatterGet.date(from: "2019-03-11 17:01:26")
Required output :
Date object of format type "yyyy-MM-dd"
It is important to note that I have only date objects and no string.
You have a date of type String, not Date.
You use one DateFormatter to convert it to Date (check that the DateFormatter doesn't return nil).
Then you use another DateFormatter to convert the Date to a string.
Please don't use "dateComponents" as a variable name. You never, ever touch date components in your code. And you don't need to specify the type, just "let date = ..." or better "if let date = ..." checking for nil.
you can use like this:
let now = Date().UTCToLocalDateConvrt(format: "yyyy-MM-dd HH:mm:ss",convertedFormat : "yyyy-MM-dd")
put below function in Date extension class:
extension Date {
func UTCToLocalDateConvrt(format: String,convertedFormat: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let timeStamp = dateFormatter.string(from: self)
dateFormatter.dateFormat = convertedFormat
guard let date = dateFormatter.date(from: timeStamp)else{
return Date()
}
return date
}
}
func formatDate(yourDate: String) -> String { // "yyyy-MM-dd HH:mm:ss"
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" // here you can change the format that enters the func
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd" // here you can change the format that exits the func
if let date = dateFormatterGet.date(from: yourDate) {
return dateFormatterPrint.string(from: date)
} else {
return nil
}
}
use it like this:
formatDate(yourDate: "2019-03-11 17:01:26")
it will return an optional string, that can be nil, make sure you are safety unwrap it (if let , guard let)
answer based on link

Date in Swift 3 conversion

I want this date "2016-10-18 22:06:20 +0000" to "18-10-2016", is this possible? I managed to get the date as follows:
var formatter = DateFormatter()
formatter.dateFormat = "yyy-MM-dd'HH:mm:ss.SSSZ"
let stringDate = formatter.string(from: currentDate)
The above gives me "10/18/16", but how can I get "18-10-2016"?
Solution in Swift 3
extension Foundation.Date {
func dashedStringFromDate() -> String {
let dateFormatter = DateFormatter()
let date = self
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.string(from: date)
}
}
Example
let date = Foundation.Date()
let formatedDate = date.dashedStringFromDate()
Little about what you put in your question makes a lot of sense. You don't have a date as 2016-10-18 22:06:20 +0000. The code you posted converts a current Date into a string. But you claim you want that string to be in the format 18-10-2016 but your code uses a completely different format.
Why not just do:
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate = formatter.string(from: currentDate)
This will convert the currentDate to a string in the format you mention in your question.
If you really have a string in the format of 2016-10-18 22:06:20 +0000 and you want to convert it to 18-10-2016, then you want two date formatters.
The first convert that original string to a date:
let string = "2016-10-18 22:06:20 +0000"
let formatter1 = DateFormatter()
formatter1.locale = Locale(identifier: "en_US_POSIX") // if this string was from web service or a database, you should set the locale
formatter1.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
guard let date = formatter1.date(from: string) else {
fatalError("Couldn't parse original date string")
}
If you then want to build a new string in the format of 18-10-2016, then you'd use a second formatter:
let formatter2 = DateFormatter()
formatter2.dateFormat = "dd-MM-yyyy"
let result = formatter2.string(from: date)

remove time from a date like this 2016-02-10 00:00:00

hello I have a date like this
2016-02-10 00:00:00
I want to get only date from it in this style
14.05.2016 or 14-05-2016
This is what I have tried
let dateFormatter = NSDateFormatter()
let date = "2016-02-10 00:00:00"
dateFormatter.dateFormat = "dd-MM-yyyy"
let newdate = dateFormatter.dateFromString(date)
print(newdate) //nil is coming
A better way than proposed versions is not to convert from date using a string formatter, but instead using calendar:
public func removeTimeStamp(fromDate: Date) -> Date {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
fatalError("Failed to strip time from Date object")
}
return date
}
Using an extension on the Date:
extension Date {
public var removeTimeStamp : Date? {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: self)) else {
return nil
}
return date
}
}
Usage:
let now = Date()
let nowWithouTime = now.removeTimeStamp
okay I solved this myself
let date = "2016-02-10 00:00:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let dateFromString : NSDate = dateFormatter.dateFromString(date)!
dateFormatter.dateFormat = "dd-MM-yyyy"
let datenew= dateFormatter.stringFromDate(dateFromString)
print(datenew)
Your code is not correct.
If you have NSDate instance that you want to convert to String using NSDateFormatter
You use this code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateString = dateFormatter.stringFromDate(date)
The problem in your code is that you have a date string with value 2016-02-10 00:00:00 but you parse it using date format `dd-MM-yyyy' this is why you get a nil Date.
Instead you need to parse it first using dateFormatter.dateFormat = "yyy-MM-dd hh:mm:ss"
Swift 5.5+
Use formatted(_:)
let now = Date.now
let date = now.formatted(.iso8601.year().month().day().dateSeparator(.dash))
Or formatted(date:time:)
let now = Date.now
let date = now.formatted(date: .abbreviated, time: .omitted)
Instead of .abbreviated, you may use a DateStyle such as .long, or .numeric.
https://developer.apple.com
If you have an input date string (or rather, date-and-time string) in one format and you want to output in a different format then you need 2 date formatters: An input formatter that takes the source string format and converts it to an NSDate (using dateFromString) and then an output formatter that takes the NSDate and converts it to your output date string (using stringFromDate).
Your code is wrong because you are creating a date formatter configured for your output date string format and trying to use it to convert your input date string to an NSDate.
I am not an expert on NSDateFormatter date strings. Any time I need to work with them I have to dig out the docs and figure out the solution to the specific problem I'm trying to solve. Thus I'm going to leave that part of the problem to you. Suffice it to say that you'll need an input date formatter that uses a format string that exactly matches the format of your input date string. This can be tricky because if it isn't exactly correct it simply fails and returns a nil NSDate.
The output date formatter is easier because if it isn't quite right, your output date will not look the way you want it to look but that will be obvious.
Recommend you to use library SwiftDate with dozen of handy options.
For your case use date truncating e.g.:
let date = "2017-07-22 15:03:50".toDate("yyyy-MM-dd HH:mm:ss", region: rome)
let truncatedTime = date.dateTruncated(from: .hour) // 2017-07-22T00:00:00+02:00
For Swift 4 and above, You can go with the following code
let date = "2016-02-10 00:00:00"
let dateFormatter = DateFormatter()
let date = modelDeals.dealItemInDetail?.validTo ?? ""
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let dateFromString : NSDate = dateFormatter.date(from: date)! as NSDate
dateFormatter.dateFormat = "dd-MM-yyyy"
let datenew = dateFormatter.string(from: dateFromString as Date)
For swift : (Swift 3) applications,
if you are using Date() objects make sure you set timeStyle
of DateFormatter() to none
Example:
let today = Date()
let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "yyyy-MM-dd", upto you
dateFormatter.dateFormat = "dd-MM-yyyy"
//This is Important!
dateFormatter.timeStyle = DateTimeFormatter.Style.none
let dateString = dateFormatter.string(from: today)
Swift 3 Version:
let date = "2016-02-10"
let dateformater = DateFormatter()
dateformater.dateFormat = "YYYY-MM-dd"
let dateString = dateformater.date(from: date)
//print date
print(dateString)

Resources