Related
How do I convert, NSDate to NSString so that only the year in #"yyyy" format is output to the string?
How about...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"];
//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
//unless ARC is active
[formatter release];
Swift 4.2 :
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
I don't know how we all missed this: localizedStringFromDate:dateStyle:timeStyle:
NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterFullStyle];
NSLog(#"%#",dateString);
outputs '13/06/12 00:22:39 GMT+03:00'
Hope to add more value by providing the normal formatter including the year, month and day with the time.
You can use this formatter for more than just a year
[dateFormat setDateFormat: #"yyyy-MM-dd HH:mm:ss zzz"];
there are a number of NSDate helpers on the web, I tend to use:
https://github.com/billymeltdown/nsdate-helper/
Readme extract below:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
This produces the following kinds of output:
‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)
In Swift:
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:#"yyyy"]; // Date formater
NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
NSLog(#"date :%#",date);
If you don't have NSDate -descriptionWithCalendarFormat:timeZone:locale: available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftime and monkey around with some C-style strings. You can get the UNIX timestamp from an NSDate using NSDate -timeIntervalSince1970.
+(NSString*)date2str:(NSDate*)myNSDateInstance onlyDate:(BOOL)onlyDate{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
if (onlyDate) {
[formatter setDateFormat:#"yyyy-MM-dd"];
}else{
[formatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
}
//Optionally for time zone conversions
// [formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
return stringFromDate;
}
+(NSDate*)str2date:(NSString*)dateStr{
if ([dateStr isKindOfClass:[NSDate class]]) {
return (NSDate*)dateStr;
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
return date;
}
Just add this extension:
extension NSDate {
var stringValue: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yourDateFormat"
return formatter.stringFromDate(self)
}
}
If you are on Mac OS X you can write:
NSString* s = [[NSDate date] descriptionWithCalendarFormat:#"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];
However this is not available on iOS.
It's swift format :
func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: calndarIdentifier)
formatter.dateFormat = dateFormat
return formatter
}
//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018
swift 4 answer
static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
let date = dateFormatter.date(from: strDate)
return date!
}
public static func dateToString(inputdate : Date) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
return formatter.string(from: inputdate)
}
Use extension to have clear code
You can write an extension to convert any Date object to any desired calendar and any format
extension Date{
func asString(format: String = "yy/MM/dd HH:mm",
for identifier: Calendar.Identifier = .persian) -> String {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: identifier)
formatter.dateFormat = format
return formatter.string(from: self)
}
}
Then use it like this:
let now = Date()
print(now.asString()) // prints -> 00/04/18 20:25
print(now.asString(format: "yyyy/MM/dd")) // prints -> 1400/04/18
print(now.asString(format: "MM/dd", for: .gregorian)) // prints -> 07/09
To learn how to specify your desired format string take a look at this link.
For a complete reference on how to format dates see Apple's official Date Formatting Guide here.
Simple way to use C# styled way to convert Date to String.
usage:
let a = time.asString()
// 1990-03-25
let b = time.asString("MM ∕ dd ∕ yyyy, hh꞉mm a")
// 03 / 25 / 1990, 10:33 PM
extensions:
extension Date {
func asString(_ template: String? = nil) -> String {
if let template = template {
let df = DateFormatter.with(template: template)
return df.string(from: self)
}
else {
return globalDateFormatter.string(from: self)
}
}
}
// Here you can set default template for DateFormatter
public let globalDateFormatter: DateFormatter = DateFormatter.with(template: "y-M-d")
public extension DateFormatter {
static func with(template: String ) -> DateFormatter {
let df = DateFormatter()
df.dateFormat = template
return df
}
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:myNSDateInstance];
NSInteger year = [components year];
// NSInteger month = [components month];
NSString *yearStr = [NSString stringWithFormat:#"%ld", year];
Define your own utility for format your date required date format
for eg.
NSString * stringFromDate(NSDate *date)
{ NSDateFormatter *formatter
[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM ∕ dd ∕ yyyy, hh꞉mm a"];
return [formatter stringFromDate:date];
}
#ios #swift #convertDateinString
Simply just do like this to "convert date into string" as per format you passed:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-YYYY" // pass formate here
let myString = formatter.string(from: date) // this will convert Date in String
Note: You can specify different formats such like "yyyy-MM-dd", "yyyy", "MM" etc...
Update for iOS 15
iOS 15 now supports calling .formatted on Date objects directly without an explicit DateFormatter.
Example for common formats
Documentation
date.formatted() // 6/8/2021, 7:30 PM
date.formatted(date: .omitted, time: .complete) // 19:30
date.formatted(date: .omitted, time: .standard) // 07:30 PM
date.formatted(date: .omitted, time: .shortened) // 7:30 PM
date.formatted(date: .omitted, time: .omitted)
Alternative syntax
Documentation
// We can also specify each DateComponent separately by chaining modifiers.
date.formatted(.dateTime.weekday(.wide).day().month().hour().minute())
// Tuesday, Jun 8, 7:30 pm
// Answer to specific question
date.formatted(.dateTime.year())
for Objective-C:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = #"yyyy";
NSString *dateString = [formatter stringFromDate:date];
for Swift:
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let dateString = formatter.string(from: now)
That's a good website for nsdateformatter.You can preview date strings with different DateFormatter in different local.
I have referred lot of links but could not find the solution hence asking it again.I have string which i need to convert into date format. Below is example
Input string : "1410271500"
In above string 14 is for 2014
10 is for Oct
27 is day
1500 is 3:00 PM
Output string : "2014-10-27 03:00:00"
Input string in not in long-integer format.
Thanks
do like
NSString *getMilliSec = #"1410271500";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyMMddHHmm"];
NSDate *getDate = [formatter dateFromString:getMilliSec];
[formatter setDateFormat:#"yyyy-MM-dd hh:mm:ss a"]; // or use yyyy-MM-dd hh:mm:ss
formatter.timeZone = [NSTimeZone systemTimeZone]; // optional
NSString *stringFromDate = [formatter stringFromDate:getDate];
swift3
let getMilliSec = "1410271500"
let formatter = DateFormatter()
formatter.dateFormat = "yyMMddHHmm"
let getDate = formatter.date(from: getMilliSec)
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss a" // or use yyyy-MM-dd hh:mm:ss
formatter.timeZone = NSTimeZone.system // optional
var stringFromDate = formatter.string(from: getDate!)
output
2015-05-29 06:10 PM convert this date into system timezone 24hrs formate
convert this date into 2015-05-29 18:10:00
You can use this code to convert 12 hour format date into 24 hours date.
NSDate *date = your date in 12 hours format;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:#"dd-MM-YYYY HH:mm"];
NSString *dateStringInTwentyHours = [dateFormatter stringFromDate:date];
For Swift 3.0
You can use this code snippet to convert 12 hour to 24 hour format.
let sourceDateString = "2015-05-29 10:40 AM"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm a"
formatter.locale = Locale(identifier: "en-US")
let date = formatter.date(from: sourceDateString)
print("\(date)")
formatter.timeZone = NSTimeZone.local
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let strDate = formatter.string(from: date!)
print(strDate)
How do I convert, NSDate to NSString so that only the year in #"yyyy" format is output to the string?
How about...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"];
//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
//unless ARC is active
[formatter release];
Swift 4.2 :
func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
I don't know how we all missed this: localizedStringFromDate:dateStyle:timeStyle:
NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterFullStyle];
NSLog(#"%#",dateString);
outputs '13/06/12 00:22:39 GMT+03:00'
Hope to add more value by providing the normal formatter including the year, month and day with the time.
You can use this formatter for more than just a year
[dateFormat setDateFormat: #"yyyy-MM-dd HH:mm:ss zzz"];
there are a number of NSDate helpers on the web, I tend to use:
https://github.com/billymeltdown/nsdate-helper/
Readme extract below:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
This produces the following kinds of output:
‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)
In Swift:
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:#"yyyy"]; // Date formater
NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
NSLog(#"date :%#",date);
If you don't have NSDate -descriptionWithCalendarFormat:timeZone:locale: available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftime and monkey around with some C-style strings. You can get the UNIX timestamp from an NSDate using NSDate -timeIntervalSince1970.
+(NSString*)date2str:(NSDate*)myNSDateInstance onlyDate:(BOOL)onlyDate{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
if (onlyDate) {
[formatter setDateFormat:#"yyyy-MM-dd"];
}else{
[formatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
}
//Optionally for time zone conversions
// [formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
return stringFromDate;
}
+(NSDate*)str2date:(NSString*)dateStr{
if ([dateStr isKindOfClass:[NSDate class]]) {
return (NSDate*)dateStr;
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
return date;
}
Just add this extension:
extension NSDate {
var stringValue: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yourDateFormat"
return formatter.stringFromDate(self)
}
}
If you are on Mac OS X you can write:
NSString* s = [[NSDate date] descriptionWithCalendarFormat:#"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];
However this is not available on iOS.
It's swift format :
func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: calndarIdentifier)
formatter.dateFormat = dateFormat
return formatter
}
//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018
swift 4 answer
static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
let date = dateFormatter.date(from: strDate)
return date!
}
public static func dateToString(inputdate : Date) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateformat
return formatter.string(from: inputdate)
}
Use extension to have clear code
You can write an extension to convert any Date object to any desired calendar and any format
extension Date{
func asString(format: String = "yy/MM/dd HH:mm",
for identifier: Calendar.Identifier = .persian) -> String {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: identifier)
formatter.dateFormat = format
return formatter.string(from: self)
}
}
Then use it like this:
let now = Date()
print(now.asString()) // prints -> 00/04/18 20:25
print(now.asString(format: "yyyy/MM/dd")) // prints -> 1400/04/18
print(now.asString(format: "MM/dd", for: .gregorian)) // prints -> 07/09
To learn how to specify your desired format string take a look at this link.
For a complete reference on how to format dates see Apple's official Date Formatting Guide here.
Simple way to use C# styled way to convert Date to String.
usage:
let a = time.asString()
// 1990-03-25
let b = time.asString("MM ∕ dd ∕ yyyy, hh꞉mm a")
// 03 / 25 / 1990, 10:33 PM
extensions:
extension Date {
func asString(_ template: String? = nil) -> String {
if let template = template {
let df = DateFormatter.with(template: template)
return df.string(from: self)
}
else {
return globalDateFormatter.string(from: self)
}
}
}
// Here you can set default template for DateFormatter
public let globalDateFormatter: DateFormatter = DateFormatter.with(template: "y-M-d")
public extension DateFormatter {
static func with(template: String ) -> DateFormatter {
let df = DateFormatter()
df.dateFormat = template
return df
}
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:myNSDateInstance];
NSInteger year = [components year];
// NSInteger month = [components month];
NSString *yearStr = [NSString stringWithFormat:#"%ld", year];
Define your own utility for format your date required date format
for eg.
NSString * stringFromDate(NSDate *date)
{ NSDateFormatter *formatter
[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM ∕ dd ∕ yyyy, hh꞉mm a"];
return [formatter stringFromDate:date];
}
#ios #swift #convertDateinString
Simply just do like this to "convert date into string" as per format you passed:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-YYYY" // pass formate here
let myString = formatter.string(from: date) // this will convert Date in String
Note: You can specify different formats such like "yyyy-MM-dd", "yyyy", "MM" etc...
Update for iOS 15
iOS 15 now supports calling .formatted on Date objects directly without an explicit DateFormatter.
Example for common formats
Documentation
date.formatted() // 6/8/2021, 7:30 PM
date.formatted(date: .omitted, time: .complete) // 19:30
date.formatted(date: .omitted, time: .standard) // 07:30 PM
date.formatted(date: .omitted, time: .shortened) // 7:30 PM
date.formatted(date: .omitted, time: .omitted)
Alternative syntax
Documentation
// We can also specify each DateComponent separately by chaining modifiers.
date.formatted(.dateTime.weekday(.wide).day().month().hour().minute())
// Tuesday, Jun 8, 7:30 pm
// Answer to specific question
date.formatted(.dateTime.year())
for Objective-C:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = #"yyyy";
NSString *dateString = [formatter stringFromDate:date];
for Swift:
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let dateString = formatter.string(from: now)
That's a good website for nsdateformatter.You can preview date strings with different DateFormatter in different local.
How would I convert an NSString like "01/02/10" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDate back into a string?
Swift 4 and later
Updated: 2018
String to Date
var dateString = "02-03-2017"
var 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 = "dd-MM-yyyy"
//`date(from:)` returns an optional so make sure you unwrap when using.
var dateFromString: Date? = dateFormatter.date(from: dateString)
Date to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
guard let unwrappedDate = dateFromString else { return }
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString)
Swift 3
Updated: 20th July 2017
String to NSDate
var dateString = "02-03-2017"
var 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 = "dd-MM-yyyy"
var dateFromString = dateFormatter.date(from: dateString)
NSDate to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.string(from: dateFromString)
Swift
Updated: 22nd October 2015
String to NSDate
var dateString = "01-02-2010"
var dateFormatter = NSDateFormatter()
// this is imporant - we set our input date format to match our input string
dateFormatter.dateFormat = "dd-MM-yyyy"
// voila!
var dateFromString = dateFormatter.dateFromString(dateString)
NSDate to String
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(NSDate())
println(stringDate)
Objective-C
NSString to NSDate
NSString *dateString = #"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"%#", stringDate);
UPDATE 2019 (Swift 4):
Made a Date extension for that. It uses NSDataDetector instead of NSDateFormatter.
// Just throw at it without any format.
var date: Date? = Date.FromString("02-14-2019 17:05:05")
Pretty enjoyable, it even recognizes things like "Tomorrow at 5".
XCTAssertEqual(Date.FromString("2019-02-14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019.02.14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019/02/14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("20190214"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02-14-2019"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02.14.2019 5:00 PM"), Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02/14/2019 17:00"), Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("14 February 2019 at 5 hour"), Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05"), Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("17:05, 14 February 2019 (UTC)"), Date.FromCalendar(2019, 2, 14, 17, 05))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05 GMT"), Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("02-13-2019 Tomorrow"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th Tomorrow at 5"), Date.FromCalendar(2019, 2, 14, 17))
Goes like:
extension Date
{
public static func FromString(_ dateString: String) -> Date?
{
// Date detector.
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
// Enumerate matches.
var matchedDate: Date?
var matchedTimeZone: TimeZone?
detector.enumerateMatches(
in: dateString,
options: [],
range: NSRange(location: 0, length: dateString.utf16.count),
using:
{
(eachResult, _, _) in
// Lookup matches.
matchedDate = eachResult?.date
matchedTimeZone = eachResult?.timeZone
// Convert to GMT (!) if no timezone detected.
if matchedTimeZone == nil, let detectedDate = matchedDate
{ matchedDate = Calendar.current.date(byAdding: .second, value: TimeZone.current.secondsFromGMT(), to: detectedDate)! }
})
// Result.
return matchedDate
}
}
UPDATE 2014:
Made an NSString extension for that.
// Simple as this.
date = dateString.dateValue;
Thanks to NSDataDetector, it recognizes a whole lot of format.
'2014-01-16' dateValue is <2014-01-16 11:00:00 +0000>
'2014.01.16' dateValue is <2014-01-16 11:00:00 +0000>
'2014/01/16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16th' dateValue is <2014-01-16 11:00:00 +0000>
'20140116' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014' dateValue is <2014-01-16 11:00:00 +0000>
'01.16.2014' dateValue is <2014-01-16 11:00:00 +0000>
'01/16/2014' dateValue is <2014-01-16 11:00:00 +0000>
'16 January 2014' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014 17:05:05' dateValue is <2014-01-16 16:05:05 +0000>
'01-16-2014 T 17:05:05 UTC' dateValue is <2014-01-16 17:05:05 +0000>
'17:05, 1 January 2014 (UTC)' dateValue is <2014-01-01 16:05:00 +0000>
Part of eppz!kit, grab the category NSString+EPPZKit.h from GitHub.
ORIGINAL ANSWER 2013:
Whether you're not sure (or don't care) about the date format contained in the string, use NSDataDetector for parsing date.
//Role players.
NSString *dateString = #"Wed, 03 Jul 2013 02:16:02 -0700";
__block NSDate *detectedDate;
//Detect.
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
[detector enumerateMatchesInString:dateString
options:kNilOptions
range:NSMakeRange(0, [dateString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{ detectedDate = result.date; }];
When using fixed-format dates you need to set the date formatter locale to "en_US_POSIX".
Taken from the Data Formatting Guide
If you're working with fixed-format dates, you should first set the
locale of the date formatter to something appropriate for your fixed
format. In most cases the best locale to choose is en_US_POSIX, a
locale that's specifically designed to yield US English results
regardless of both user and system preferences. en_US_POSIX is also
invariant in time (if the US, at some point in the future, changes the
way it formats dates, en_US will change to reflect the new behavior,
but en_US_POSIX will not), and between platforms (en_US_POSIX works
the same on iPhone OS as it does on OS X, and as it does on other
platforms).
Swift 3 or later
extension Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd/MM/yy"
return formatter
}()
static let time: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm"
return formatter
}()
static let weekdayName: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "cccc"
return formatter
}()
static let month: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "LLLL"
return formatter
}()
}
extension Date {
var customDate: String {
return Formatter.customDate.string(from: self)
}
var customTime: String {
return Formatter.time.string(from: self)
}
var weekdayName: String {
return Formatter.weekdayName.string(from: self)
}
var monthName: String {
return Formatter.month.string(from: self)
}
}
extension String {
var customDate: Date? {
return Formatter.customDate.date(from: self)
}
}
usage:
// this will be displayed like this regardless of the user and system preferences
Date().customTime // "16:50"
Date().customDate // "06/05/17"
// this will be displayed according to user and system preferences
Date().weekdayName // "Saturday"
Date().monthName // "May"
Parsing the custom date and converting the date back to the same string format:
let dateString = "01/02/10"
if let date = dateString.customDate {
print(date.customDate) // "01/02/10\n"
print(date.monthName) // customDate
}
Here it is all elements you can use to customize it as necessary:
Why not add a category to NSString?
// NSString+Date.h
#interface NSString (Date)
+ (NSDate*)stringDateFromString:(NSString*)string;
+ (NSString*)stringDateFromDate:(NSDate*)date;
#end
// NSString+Date.m
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *date = [dateFormatter dateFromString:stringDate ];
[dateFormatter release];
+ (NSDateFormatter*)stringDateFormatter
{
static NSDateFormatter* formatter = nil;
if (formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
}
return formatter;
}
+ (NSDate*)stringDateFromString:(NSString*)string
{
return [[NSString stringDateFormatter] dateFromString:string];
}
+ (NSString*)stringDateFromDate:(NSDate*)date
{
return [[NSString stringDateFormatter] stringFromDate:date];
}
// Usage (#import "NSString+Date.h") or add in "YOUR PROJECT".pch file
NSString* string = [NSString stringDateFromDate:[NSDate date]];
NSDate* date = [NSString stringDateFromString:string];
using "10" for representing a year is not good, because it can be 1910, 1810, etc. You probably should use 4 digits for that.
If you can change the date to something like
yyyymmdd
Then you can use:
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
NSString *dateStr = #"Tue, 25 May 2010 12:53:58 +0000";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];
// Convert string to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert Date to string
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
NSString *mystr=#"Your string date";
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [dateFormatter dateFromString:mystr];
Nslog(#"%#",now);
If you want set the format use below code:
NSString *dateString = #"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is important - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
Nslog(#"%#",[dateFormatter dateFromString:dateString]);
Use this method to convert from NSString to NSdate:
-(NSDate *)getDateFromString:(NSString *)pstrDate
{
NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate* myDate = [myFormatter dateFromString:pstrDate];
return myDate;
}
If anyone is interested in doing something like this in Swift these days, I have a start on something, although it's not perfect.
func detectDate(dateString: NSString) -> NSDate {
var error: NSError?
let detector: NSDataDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)!
if error == nil {
var matches = detector.matchesInString(dateString, options: nil, range: NSMakeRange(0, dateString.length))
let currentLocale = NSLocale.currentLocale()
for match in matches {
match.resultType == NSTextCheckingType.Date
NSLog("Date: \(match.date.description)")
return match.date
}
}
return NSDate()
}
Date to NSString
NSString *dateString = [NSString stringWithFormat:#"%#",[NSDate date]];
NSLog(#"string: %#",dateString ); //2015-03-24 12:28:49 +0000
NSString to NSDate
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"date: %#", date); //015-03-24 12:28:49 +0000
You can use extensions for this.
extension NSDate {
//NSString to NSDate
convenience
init(dateString:String) {
let nsDateFormatter = NSDateFormatter()
nsDateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
// Add the locale if required here
let dateObj = nsDateFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:dateObj!)
}
//NSDate to time string
func getTime() -> String {
let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "hh:mm"
//Can also set the default styles for date or time using .timeStyle or .dateStyle
return timeFormatter.stringFromDate(self)
}
//NSDate to date string
func getDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMM"
return dateFormatter.stringFromDate(self)
}
//NSDate to String
func getString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
return dateFormatter.stringFromDate(self)
}
}
So while execution actual code will look like follows
var dateObjFromString = NSDate(dateString: cutDateTime)
var dateString = dateObjFromString.getDate()
var timeString = dateObjFromString.getTime()
var stringFromDate = dateObjFromString.getString()
There are some defaults methods as well but I guess it might not work for the format you have given from documentation
-dateFromString(_:)
-stringFromDate(_:)
-localizedStringFromDate(_ date: NSDate,
dateStyle dateStyle: NSDateFormatterStyle,
timeStyle timeStyle: NSDateFormatterStyle) -> String
Best practice is to build yourself a general class where you put all your general use methods, methods useful in almost all projects and there add the code suggested by #Pavan as:
+ (NSDate *)getDateOutOfString:(NSString *)passedString andDateFormat:(NSString *)dateFormat{
NSString *dateString = passedString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateFormat];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}
.. and so on for all other useful methods
By doing so you start building a clean reusable code for you app.
Cheers!
As per Swift 2.2
You can get easily NSDate from String and String from NSDate.
e.g.
First set date formatter
let formatter = NSDateFormatter();
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
formatter.timeStyle = .NoStyle
formatter.dateFormat = "MM/dd/yyyy"
Now get date from string and vice versa.
let strDate = formatter.stringFromDate(NSDate())
print(strDate)
let dateFromStr = formatter.dateFromString(strDate)
print(dateFromStr)
Now enjoy.
NSString to NSDate or NSDate to NSString
//This method is used to get NSDate from string
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate {
// Converted date from date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[dateFormatter setDateFormat:formate];
NSDate *convertedDate = [dateFormatter dateFromString:dateString];
return convertedDate;
}
//This method is used to get the NSString for NSDate
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate {
// Converted date from date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[dateFormatter setDateFormat:formate];
NSString *convertedDate = [dateFormatter stringFromDate:date];
return convertedDate;
}
The above examples aren't simply written for Swift 3.0+
Update - Swift 3.0+ - Convert Date To String
let date = Date() // insert your date data here
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like
var dateString = dateFormatter.string(from: date)
String To Date
var dateFormatter = DateFormatter()
dateFormatter.format = "dd/MM/yyyy"
var dateFromString: Date? = dateFormatter.date(from: dateString) //pass string here
Date To String
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let newDate = dateFormatter.string(from: date) //pass Date here