263

How do I convert, NSDate to NSString so that only the year in @"yyyy" format is output to the string?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
4thSpace
  • 43,672
  • 97
  • 296
  • 475

19 Answers19

474

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)
}
Sunil Targe
  • 7,251
  • 5
  • 49
  • 80
Allan
  • 4,808
  • 1
  • 17
  • 4
  • 24
    This will produce a memory leak, since the formatter is never released. – mana Jun 22 '10 at 08:46
  • 6
    Don't use `init` with `NSDateFormatter`. It was [removed after iOS 3.2](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/DeprecationAppendix/AppendixADeprecatedAPI.html%23//apple_ref/occ/instm/NSDateFormatter/init). (And if you use a class method instead, it will autorelease and you won't have the leak problem, too.) – zekel Nov 08 '10 at 05:20
  • 3
    Really suggest looking below at localizedStringFromDate – Oded Ben Dov Jun 12 '12 at 21:24
  • 4
    @zekel I'm not sure what the documentation used to say, but now it suggests `init` in multiple places. – Neal Ehardt Aug 20 '12 at 21:03
  • 2
    I would have autoreleased it (3 years ago) – Adam Waite Mar 07 '14 at 14:46
  • iOS7 uses this pattern for formatting: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns – Krešimir Prcela Dec 18 '14 at 13:23
284

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'

Oded Ben Dov
  • 9,936
  • 6
  • 38
  • 53
  • once written out to a string, is there a nice neat way to read it in like this? (using those NSDateFormatter enums) – Fonix Nov 20 '13 at 10:21
  • @Fonix I don't think so - this is a localized string, which means it depends on the user's locale settings. You should never store dates in a format like this because the settings can change any time. – Viktor Benei May 20 '14 at 16:57
  • Its nice if you use the formatter rare. Otherwise you need a cache. – Mike Glukhov Jan 14 '15 at 07:03
  • In swift: let dateString = NSDateFormatter.localizedStringFromDate(date, dateStyle: .ShortStyle, timeStyle: .FullStyle); – Cristan Feb 22 '16 at 17:23
  • 1
    Reduced the number of codes and thanks its working perfect – Preetha Jun 14 '16 at 07:07
87

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"]; 
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Al Pascual
  • 1,241
  • 9
  • 7
25

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 ;-)
Venk
  • 5,949
  • 9
  • 41
  • 52
Nik Burns
  • 3,363
  • 2
  • 29
  • 37
  • This is definitely a great solution. Don't have to waste time worrying about how you want your dates to look, and can get on with coding. :) – kyleturner Oct 15 '12 at 16:34
14

In Swift:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
Dave Patrick
  • 278
  • 3
  • 8
8
  NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
  [dateformate setDateFormat:@"yyyy"]; // Date formater
  NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
  NSLog(@"date :%@",date);
Steve Moser
  • 7,647
  • 5
  • 55
  • 94
Soumya Ranjan
  • 4,817
  • 2
  • 26
  • 51
5
+(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;
}
Gank
  • 4,507
  • 4
  • 49
  • 45
5

Just add this extension:

extension NSDate {
    var stringValue: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yourDateFormat"
        return formatter.stringFromDate(self)
    }
}
Nazariy Vlizlo
  • 778
  • 7
  • 16
5

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.

Venk
  • 5,949
  • 9
  • 41
  • 52
pix0r
  • 31,139
  • 18
  • 86
  • 102
2

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.

neoneye
  • 50,398
  • 25
  • 166
  • 151
1

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
amin
  • 313
  • 1
  • 10
1

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)

}
1

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.

Mehdi Ijadnazar
  • 4,532
  • 4
  • 35
  • 35
1

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
    }
}
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
0
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];
Shamsiddin Saidov
  • 2,281
  • 4
  • 23
  • 35
0

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]; 
}
Ash
  • 5,525
  • 1
  • 40
  • 34
0

#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...

fcdt
  • 2,371
  • 5
  • 14
  • 26
0

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())
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
0

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.

enter image description here

Jules
  • 631
  • 6
  • 14