[objective-c] Convert NSDate to NSString

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

This question is related to objective-c swift nsstring nsdate

The answer is


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.


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];

In Swift:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)

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.


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 ;-)

Just add this extension:

extension NSDate {
    var stringValue: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yourDateFormat"
        return formatter.stringFromDate(self)
    }
}

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


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'


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

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]; 
}

  NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
  [dateformate setDateFormat:@"yyyy"]; // Date formater
  NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
  NSLog(@"date :%@",date);

+(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;
}

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)

}

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to nsstring

NSRange to Range<String.Index> Creating NSData from NSString in Swift How do I check if a string contains another string in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How do I URL encode a string Objective-C and Swift URL encoding Convert an NSURL to an NSString Remove all whitespaces from NSString

Examples related to nsdate

Get current date in Swift 3? How to get time (hour, minute, second) in Swift 3 using NSDate? Convert string to date in Swift Date Format in Swift How to convert string to date to string in Swift iOS? Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift Get day of week using NSDate Get UTC time and local time from NSDate object How can I convert string date to NSDate? How do you create a Swift Date object?