2016-08-29 45 views
0

我寫了一個函數來獲取UTC時間字符串,該字符串對應於作爲參數傳遞給函數的任何時間字符串。隨時獲取UTC時間以及處理夏令時以及

+(NSString *)getUTCTime:(NSString *)selectedTime 
{ 
    NSString *strFormat; 
    if ([self is24HourFormat:selectedTime]){ 
     strFormat = @"HH:mm"; 
    } 
    else{ 
     strFormat = @"hh:mm a"; 
    } 
    NSLocale *baseLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 

    NSDateFormatter *dateFormatterlocal = [[NSDateFormatter alloc] init]; 
    [dateFormatterlocal setTimeZone:[NSTimeZone systemTimeZone]]; 
    dateFormatterlocal.locale = baseLocale; 
    [dateFormatterlocal setDateFormat:strFormat]; 

    NSDate *selectedDate = [dateFormatterlocal dateFromString:selectedTime]; 

    NSDateFormatter *dateFormatterUTC = [[NSDateFormatter alloc] init]; 
    [dateFormatterUTC setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 
    dateFormatterUTC.locale = baseLocale; 
    [dateFormatterUTC setDateFormat:strFormat]; 


    NSString *utcTimeString = [dateFormatterUTC stringFromDate:selectedDate]; 
    return utcTimeString; 
} 

它在印度孟買時區正常工作。但是,如果我將時區更改爲倫敦,它將返回給我的同時,我正在傳遞函數參數。目前在倫敦是UTC + 1。 NSDateFormatter是否可以處理夏令時?

+0

究竟需要什麼?你想用utc格式的時間嗎? – Lion

+0

我需要將用戶選擇的時間對應的UTC時間發送到服務器。 –

+0

按照定義,UTC沒有時區。我認爲你的意思是GMT + 1。 – Avi

回答

1

您可以使用NSTimeZone方法如下所示夏令:見NSTimeZone Class Reference

  1. isDaylightSavingTimeForDate: //會告訴你,如果在此日期
  2. 日光節約存在daylightSavingTimeOffset//會告訴你夏令時有多少偏移量

使用下面的代碼它正確地返回日光節省與偏移

var timeZone:NSTimeZone = NSTimeZone(name:"Europe/London")! 
print(timeZone.daylightSavingTime) //this will return true if day light saving present 
print(timeZone.daylightSavingTimeOffset/(60*60))//this will give you number of hours by which the day light saving offset should be 
print("timezone: \(timeZone)")//will give you detail about timezone 
+0

對於倫敦時區,它返回0.000偏移量。但現在在倫敦是UTC + 1。 –

+0

@VarunMehta我已經更新了**評論**並在操場上進行了測試,效果很好,併爲我提供了歐洲/倫敦的1個膠印。檢查上面的代碼和一切最好的。 –