How to convert Date like “2012-12-26” to “december

2020-07-25 12:52发布

I want to convert date 2012-12-26 to december 26, 2012 in iOS?

I am using websrvice and the data comes in this format 1990-12-26.

I want to change this to december 26, 2012 format.

This is what I am doing:

lbl_Rightside.text = [rootElement stringValueForNode:@"date"];
NSLog(@"lbl_Rightside is %@",lbl_Rightside.text);
[lbl_Rightside release];

Getting date to this label on 1990-12-26. Now I want to change date to december 26, 2012 format.

Any hints from experts would be very welcome.

4条回答
男人必须洒脱
2楼-- · 2020-07-25 13:11

Try to look at NSDateFormatter Class,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];  // this is your input date format
NSDate *newDate = [dateFormatter dateFromString:dateString];//converting string to date object

The format you are looking for is something like:

[dateFormatter setDateFormat:@"MMM dd,yyy"]; // setting new format
NSLog(@"The date is = %@",[dateFormatter stringFromDate:newDate])
查看更多
Anthone
3楼-- · 2020-07-25 13:20

you can use NSDateFormatter to do this kind of things. First

  1. convert your date String to a date object using dateFromString: method.
  2. from date convert to string you want using stringFromDate: method
  3. Different format strings can be found here.

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *orignalDate   =  [dateFormatter dateFromString:YOUR_ORIGINAL_STRING];
    
    [dateFormatter setDateFormat:@"MMMM dd, yyyy"];
     NSString *finalString = [dateFormatter stringFromDate:orignalDate];
    
    [dateFormatter release]; //if not using ARC
    
查看更多
【Aperson】
4楼-- · 2020-07-25 13:20

by using NSDateFormatter

NSString to NSDate

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - 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:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDate convert to NSString:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);
[dateFormatter release];
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-07-25 13:28

Check the official Apple documentation about NSDateFormatter. You should use this class to do this kind of formatting.

查看更多
登录 后发表回答