[英]iOS 7: Convert NSDate to string with custom timezone and get back new NSDate
我希望修改當前系統時間(設置自定義NSTimeZone
)並返回一個新的NSDate
對象。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSLog(@"System time: %@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Aqtobe"]];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Aqtobe time: %@", dateString);
System time: 2014-02-05 10:00:46 +0000
Aqtobe time: 2014-02-05 15:00:46 +0500
但是,如果我嘗試從Aqtobe時間獲取新的NSDate對象:
NSLog(@"New NSDate: %@", [dateFormatter dateFromString:dateString]);
我懂了
New NSDate: 2014-02-05 10:02:40 +0000
我哪里錯了? 提前致謝
NSDate始終以格林尼治標准時間+0:00返回日期。 因此,它(NSDate對象)始終具有正確的轉換值,但在格林尼治標准時間+0:00。 因此,要將其用作文本,您將始終必須在相同區域中使用相同的日期格式。 如果要在其他位置(超出dateformatter對象范圍)使用date作為日期中的字符串,則最好使用特殊的轉換方法。
下面用示例清楚地說明:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
NSLog(@"System time: %@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Aqtobe"]];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Aqtobe time: %@", dateString);
// date will always contain value in GMT +0:00
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"New NSDate (NSDate): %@", [dateFormatter stringFromDate:date]);
// converts date into string
NSLog(@"New NSDate (NSString): %@", [dateFormatter stringFromDate:date]);
有關詳細說明,您可以參考以下問題: [NSDate date]是否返回本地日期和時間?
NSDate
有許多比較日期的方法,例如isEqualToDate:
有關方法和用法的更多詳細信息,請參見SO問題 )。 我從這里開始采用的此方法將使您確定date
是否在firstDate
和lastDate
之間。
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return [date compare:firstDate] == NSOrderedDescending &&
[date compare:lastDate] == NSOrderedAscending;
}
我希望這就是你的意思。 如果沒有,請確切說明您要做什么。
您可以使用NSDateComponents
和NSCalendar
創建新日期。 從日期和時間編程指南
創建帶時區的日期
時區在確定日期何時起着重要的作用。 考慮一個跟蹤約會的簡單日歷應用程序。 例如,假設您住在芝加哥,並且在星期二上午10:00預約牙醫。 但是,您將在星期日和星期一在紐約。 創建約會時,它是用絕對時間的心態完成的。 該時間是美國中部時間10:00 AM; 當您去紐約時,該時間應顯示為11:00 AM,因為您所在的時區不同,但是絕對時間相同。 另一方面,如果您創建了一個每天早上7:00 AM醒來並鍛煉的約會,則您不希望鬧鍾僅在您去都柏林或在都柏林的旅途中在1:00 PM響起5:00 AM,因為您在洛杉磯。
NSDate對象以絕對時間存儲日期。 例如,清單16中創建的date對象表示CDT 4:00 PM,EDT 5:00等。
清單16使用特定時區從組件創建日期
NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CDT"]];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init]; [timeZoneComps setHour:16];
//specify whatever day, month, and year is appropriate
NSDate *date=[gregorian dateFromComponents:timeZoneComps];
如果需要創建獨立於時區的日期,則可以將日期存儲為NSDateComponents對象,只要存儲對相應日歷的某些引用即可。
在iOS中,NSDateComponents對象可以包含日歷,時區和日期對象。 因此,您可以將日歷與組件一起存儲。 如果您使用NSDateComponents類的date方法訪問日期,請確保相關的時區是最新的。
無論如何,請記住,日期是唯一的時間點。 向用戶顯示的內容因其區域設置和時區而異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.