简体   繁体   English

带日期的NSString:减小日期的大小

[英]NSString with date: reduce size of date

I have a NSString like Mon Feb 06 20:02:17 +0000 2012 . 我有一个NSString像Mon Feb 06 20:02:17 +0000 2012 I want to write it in a shorter way, maybe like: DD-MM-YY, HH:MM . 我想用更短的方式编写它,例如: DD-MM-YY, HH:MM I have think that maybe I can convert it to NSDate and again to a shorter NSString, but I don't know how to convert this strange date format to NSDate. 我认为也许可以将其转换为NSDate,然后再转换为较短的NSString,但是我不知道如何将这种奇怪的日期格式转换为NSDate。

If you need more information, ask me. 如果您需要更多信息,请问我。 Thanks! 谢谢!

There are similar question and answers in StackOverflow and a tutorial that may help you: StackOverflow和教程中也有类似的问题和解答,可以帮助您:

Tutorial: http://iosdevelopertips.com/cocoa/date-formatters-examples-take-3.html 教程: http//iosdevelopertips.com/cocoa/date-formatters-examples-take-3.html

Similar questions: 类似问题:

EDIT 编辑

NSString *dateStr = @"20081122"; 

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

You need to use an NSDateFormatter to tell NSDate the format the original date is in and the format you want it in, then you can convert between the two like this: 您需要使用NSDateFormatter告诉NSDate原始日期所使用的格式以及您想要的日期格式,然后您可以像这样在两者之间进行转换:

NSString *oldDate = @"Mon Feb 06 20:02:17 +0000 2012";
NSString *oldFormat = @"EEE MMM dd HH:mm:ss ZZ yyyy";

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:oldFormat];

NSDate *date = [dateFormatter dateFromString:sourceString];

NSString *newFormat = @"dd-MM-yy, HH:mm";

[dateFormatter setDateFormat:newFormat];
NSString *newDate = [dateFormatter stringFromDate:date];

Try with NSDateFormatter . 尝试使用NSDateFormatter

You can convert to NSDate using one of its method: 您可以使用其方法之一转换为NSDate:

- (NSDate *)dateFromString:(NSString *)string

And then convert that to whatever you want using NSDateFormatter. 然后使用NSDateFormatter将其转换为所需的内容。

Edit: Actually NSDate has a class method so you may check that as well: 编辑:实际上NSDate有一个类方法,所以您也可以检查一下:

+ (id)dateWithString:(NSString *)aString

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

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