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 !!
Related
I am trying to get current date and time from a unix time stamp but it keeps giving me the wrong date this is the code i am currenty
func getDateFromStamp(timeInterval:Int) -> String{
let date = NSDate(timeIntervalSince1970: TimeInterval(timeInterval))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, h:mm a"
let dateString = dateFormatter.string(from: date as Date)
return dateString
}
Usually unix timestamps are in milliseconds, but Date uses seconds. You might need to divide your timestamp by 1000.
Possible errors:
I try to use milliseconds instead of seconds. timeIntervalSince1970: TimeInterval uses seconds. Divide timeInterval by 1000 beforehand.
Or you have not setup TimeZone.
Don't forget to use Date() instead of NSDate()
It depends on your results and input parameters.
EDIT
To change time zone use this code:
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+01:00")
For Swift 4:
Step:-1 Convert to Date:
let timestamp = "Your TimeStamp here"
var dateFromTimeStamp = Date(timeIntervalSince1970: timestamp as! TimeInterval / 1000)
Step:-2 Convert to appropriate time zone:
let dateFormatter = DateFormatter();
let dateFormat = "dd MMM yyyy"; //Any TimeFormat you want
dateFormatter.dateFormat = dateFormat;
let formattedDate = dateFormatter.string(from: dateFromTimeStamp);
dateFormatter.locale = NSLocale.current;
dateFormatter.timeZone = TimeZone(abbreviation: "GMT"); //Pass Appropriate time zone here.
dateFormatter.dateFormat = dateFormat as String;
let sourceDate = dateFormatter.date(from: formattedDate as String);
print(sourceDate)
Hope so this helps You.
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)
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)
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 can i achieve this kind of format?? using "NSDateFormatter"
March 1-2 2016?
Is there a format to get day only, Month only, Year only?
let dateString = self.dateLists[indexPath.row]
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "MMMM"
let date2 = dateFormatter2.dateFromString(dateString as String)
You need the correct dateformat to get everything you want from an Datestring.
If your date is a string, you need to convert it first to an NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // the format of your string
dateFormatter.timeZone = NSTimeZone(name: "GMT")
if let date = dateFormatter.dateFromString(dateString) {
// conversation to NSDate() was successful
// now convert to anything you want
dateFormatter.dateFormat = "MMMM"
let newDateString = dateFormatter.stringFromDate(date)
}
Here are all available Dateformatters, for example:
Month only (as text):
“MMMM”
Or as 2 digit String:
“MM”
Here is all you need:
http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let str1 = "May 12 1968 04:00 PM"
let str2 = "May"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM"
let date1 = dateFormatter.dateFromString(str1) // nil
let date2 = dateFormatter.dateFromString(str2) // May 1, 2000, 12:00 AM
dateFormatter.dateFormat = "MM dd yyyy hh:mm a"
let date3 = dateFormatter.dateFromString(str1) // May 12, 1968, 04:00 PM
let date4 = dateFormatter.dateFromString(str2) // nil
check your input string ... it must conform to you format
check your locale, even though you define your custom format, the
system use the locale (gregorian vs julian calendar ... etc)
if it still doesn't work, parse you string 'manually'