简体   繁体   English

如何在iphone中将nsstring更改为nsdate格式?

[英]How to change nsstring to nsdate format in iphone?

I have struggling with to convert nsstring to nsdate format. 我一直在努力将nsstring转换为nsdate格式。 I have a date in nsstring format like (2011-08-25 18:30:00 +0000), but i want to change it in nsdate format (08/26/2011). 我有一个nsstring格式的日期,如(2011-08-25 18:30:00 +0000),但我想以nsdate格式(08/26/2011)更改它。 How to change it? 怎么改呢? Can any one help me please? 有人能帮帮我吗? Thanks in advance... I have spend one day to solve this but i cant find out the solution.. Please help me friends.... 在此先感谢...我花了一天时间来解决这个问题,但我找不到解决方案..请帮助我的朋友....

This is my code, 这是我的代码,

    NSString *dateString = @"2011-08-25 18:30:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"Converted date is %@",dateFromString);

Output is, 输出是,

         Converted date is (null)

Yuva.M Yuva.M

NSString *dateWithInitialFormat = @"2011-08-25 18:30:00 +0000";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateWithInitialFormat];

[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date];
NSLog(@"dateWithNewFormat: %@", dateWithNewFormat);

From NSLog: dateWithNewFormat: 08/25/2011 来自NSLog:dateWithNewFormat:08/25/2011

See Date Format Patterns 请参见日期格式模式

You need to use an NSDateFormatter and set the date format to match how you're storing it, like the below. 您需要使用NSDateFormatter并设置日期格式以匹配您存储它的方式,如下所示。

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *myDate = [df dateFromString: myDateString];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MMMM dd, yyyy"];
    NSDate* d = [df dateFromString:@"January 06, 1992"];
    NSLog(@"%@", d);

    NSDate *dispalyDate = d;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd MMM"];
    NSString *str = [dateFormat stringFromDate:dispalyDate];
    NSLog(@"%@", str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM