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)
Related
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"
}
Trying to show the time and date separately in Swift 3 and both fields are returning nil. I'm receiving the date as a string thats in the standard Date() format.
public func formatDateForAbandonTicket(_ dte: String) -> String {
print(dte)
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
let t = timeFormatter.date(from: dte)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d/MM/YYYY"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
let d = dateFormatter.date(from: dte)
print()
print(t)
print()
print(d)
return "\(d)" + " " + "\(t)"
}
I get a nil response from both d & t. The parameter does contain the right date "2017-11-14 16:36:29 +0000".
Thanks
Your code doesn't work because you need to first convert dte to a Date and to do that, you need to specify a format that matches the complete date string. You only need one Date, not two.
And there is no reason to create two separate strings just to combine them back into one.
public func formatDateForAbandonTicket(_ dte: String) -> String {
print(dte)
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
df.locale = Locale(identifier: "en_US_POSIX")
if let date = df.date(from: dte) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d/MM/yyyy HH:mm"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let dateStr = dateFormatter.string(from: date)
return dateStr
} else {
return ""
}
}
Also note that you are converting the result to a time in UTC time instead of the user's locale time. That's fine if that is what you need, just make sure it makes sense to the user.
I am getting date string from server like that "2017-08-05T00:30:00.000+02:00". Below is my code for date formatter.
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZZ"
dateFormatter.locale = Foundation.Locale(identifier: "en_US_POSIX")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
But it returns 2017-08-04 22:30:00 +0000. Which is wrong. Any suggestions?
In Swift 3
You can change your server time string to UTC time Date as:
let dateFormatter: DateFormatter = DateFormatter()
var serverDateString = "2017-08-05T00:30:00.000+02:00"
let index = serverDateString.index(serverDateString.startIndex, offsetBy: 19)
serverDateString = serverDateString.substring(to: index)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
Your Code for parsing date is correct: 2017-08-05T00:30:00.000+02:00 and 2017-08-04 22:30:00 +0000 represent the same time, just in different time zones. Your only problem is that Date doesn't actually store the time zone
yyyy-MM-dd'T'hh:mm:ss.SSSZZZZZZ
This is correct date formate for your input string. Here is the Apple Document for more description.
Here is my code:
var strInputDateString: String = "2017-08-05T00:30:00.000+02:00"
var dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSZZZZZZ"
//Set new dateFormate
var date1: Date? = dateFormat.date(from: strInputDateString)
dateFormat.dateFormat = "dd-MM-YYYY hh:mm:ss"
// Your Desire
var strOutputDateString: String = dateFormat.string(from: date1!)
print("\(strInputDateString)")
print("\(strOutputDateString)")
output:
Main input String:2017-08-05T00:30:00.000+02:00
Converted String: 05-08-2017 04:00:00
For now, I tried to convert your date format with my custom. It's give me the perfect output.
Actually, your code is good.
I copied your data and ran it in playground.
What kind of format you want it be?
Try this
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
dateFormatter.locale = Foundation.Locale(identifier: "en_US_POSIX")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
Hope this helps
The step you are missing is to again use your DateFormatter to format the date into a string. When you use print on the date, it will always show GMT. For illustration purposes, I've set the TimeZone to Berlin to match the original offset of +2:00.
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZZ"
// Hard set to Berlin
dateFormatter.timeZone = TimeZone(identifier: "Europe/Berlin")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
// Your missing step
dateFormatter.string(from: currentDate)
Remember that DateFormatters are about:
Parsing from a String - df.date(from: String)
Formatting from a Date - df.string(from: Date)
This question already has answers here:
Convert NSDate to NSString
(19 answers)
Closed 5 years ago.
I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.
let formatter = DateFormatter()
let myString = (String(describing: date))
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate)
you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here
for e.g , do like
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringDate = formatter.string(from: yourDate!)
print(myStringDate)
you get the output as
I always use this code while converting Date to String . (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
Your updated code.update it.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
After allocating DateFormatter you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")
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)