Can't find the right date formatter (DateFormatter) in iphone - ios

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)

Related

Format Date from String - swift3

HI I am trying to formate date from string (08-05-1988) I want to convert to date as given below, output also given below,
let dateString = "08-05-1988"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateFromString = dateFormatter.date(from: dateString)
let stringValue = String(describing: dateFromString)
out put : Optional(1988-05-07 18:30:00 +0000)
Then, I want to format the out put date from (1988-05-07 18:30:00 +0000) to other format as given below. But, when format the string to Date is nil
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd hh:mm:ss Z"
let date = dateFormatter.date(from: dateString)
let formatter = DateFormatter()
formatter.dateFormat = "dd-MMM-yyyy"
let formatedDate:String = formatter.string(from: date!)
Expected Output : 08-May-1988
The output Optional(1988-05-07 18:30:00 +0000) is the result of the description of a Date object. It's not related to any given string format.
To convert 08-05-1988 to 08-May-1988 you can simply use
let dateString = "08-05-1988"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateFromString = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "dd-MMM-yyyy"
let formatedDate = dateFormatter.string(from: dateFromString!)
let date = Date()
let format = DateFormatter()
format.dateFormat = "dd-MM-yyyy"
let formatDate = format.string(from: date)
You're calling dateFormatter.date on dateString instead of dateFromString. Since "08-05-1988" doesn't match the specified format of "yyyy-mm-dd hh:mm:ss Z", dateFormatter.date returns nil.

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)

How to convert string to date to string in Swift iOS? [duplicate]

This question already has answers here:
Converting NSString to NSDate (and back again)
(17 answers)
Closed 7 years ago.
Am learning swift and am struck in converting the date String to NSDate to string. Am getting the date string in this format "Thu, 22 Oct 2015 07:45:17 +0000". I need to show the date in the MM-dd-yyyy format. I tried the following code but, it returns "null".
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
let dateObj = dateFormatter.dateFromString(dateString!)
print("Dateobj: \(dateObj)")
Can anyone please help where am going wrong? Looking forward the help. Thanks in advance.
First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Swift 2 and below
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
And in Swift 3 and higher this would now be written as:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")

String to NSdate returns nil

I want to separate my String dateTime to different variables date and time because I will display it separately. How could I do this?
Here's my code in getting the date only and it returns nil:
let datetime = "2015-04-06T13:24:11.913"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM-DD-YYYY"
let date = dateFormatter.dateFromString(datetime)
println(date)
Thanks in advance.
Update:
This is my error,
Update 2:
It doesn't return an error but it gives me the wrong Month for the formatted date
Use this formatter
let datetime = "2015-04-06T13:24:11.913"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.dateFromString(datetime)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour, fromDate: date!)
components.day//This is 6
Your formatter have to match your string
This is my playground screenshot,it works well.
let datetime = "2015-04-06T13:24:11" //"2015-04-06T13:24:11.913"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd'T'HH:mm:ss" //"yyyy-mm-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.dateFromString(datetime)
let myTime = NSDateFormatter.localizedStringFromDate(date!, dateStyle: .NoStyle , timeStyle: .MediumStyle)
let myDate = NSDateFormatter.localizedStringFromDate(date!, dateStyle: .ShortStyle , timeStyle: .NoStyle)
println(date!)//DateWithTime
println(myDate)//Date
println(myTime)//time
This helps you for formatting.. NSDateFormatter_Class
Thanks to #LeonardoSavioDabus for given this image => Swift NSDate UTC time and local time
Besides the problem that the string you were testing had milliseconds while the date from your array has only seconds, now the problem is that Y is for week of year. You need to use lowercase "y" with the date format and also lowercase "d". The date format should look like this:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
to extract the month component from a date you can use this extension:
extension Date {
var month: Int {
Calendar(identifier: .gregorian).component(.month, from: self)
}
}
NSDate().month // 5
All of the NSDateFormatters in other answers will give the wrong date once the user sets the iOS calendar to anything other than the gregorian calendar. Your date string doesn't mention any timezone as well so I'm going to assume is UTC.
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.calendar = NSCalendar.gregorianCalendar()
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS"
Try like this way,
let datetime = "2015-04-06T13:24:11.913"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let dateFromString = dateFormatter.dateFromString(datetime)
var calendar = NSCalendar.currentCalendar()
var components:NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond | NSCalendarUnit.CalendarUnitHour, fromDate: dateFromString!)
var stringDate = "\(components.month)-\(components.day)-\(components.year)"
var stringTime = "\(components.hour):\(components.minute):\(components.second)"
println(stringDate)
println(stringTime)
You will get output Like :
4-6-2015
13:24:11
Enjoy Coding !!

Resources