2016-12-14 6 views
1

나는 우리가 사용하는 API로 보내는 NSDate 개체가 있습니다. 우리의 응용 프로그램은 전 세계에 걸쳐 사용되는, 그래서 API는 예를 들어, UTC에있을 일을하고자한다 : [NSDate date]를 현지화 된 UTC 날짜 문자열로 변환

"/Date(1481704200000)/" 

그러나, 날짜가 시간대가 API 이후 고려 상쇄 할 필요가

이/서버가 수행되지 우리를 위해서. 이 작업을 수행하지 않으면 서버에서 날짜를 볼 때 날짜가 올바르지 않습니다.

// Offset 
float timezoneoffset = [[NSTimeZone localTimeZone] secondsFromGMT]; 

// Date 
CFTimeInterval startDate = [[NSDate date] timeIntervalSince1970]; 
startDate = startDate - timezoneoffset; 
NSString *dateStarted = [NSString stringWithFormat:@"/Date(%.0f000)/", startDate]; 

가 어떻게 제대로 계정으로 로컬 시간대를 적용하고 올바른 형식의 UTC 날짜 문자열을 만들 수 있습니다

나는 잘못된 날짜를 가져 오는 것 같습니다 다음을하고 있는가?

+1

timeIntervalSince1970은 UTC로 계산됩니다. 따라서 당신은 개종 할 필요가 없습니다. https://developer.apple.com/reference/foundation/nsdate/1407504-timeintervalsince1970 – Satachito

+0

두 번째 줄에서 실수를하는 것 같습니다. NSLog에서 timezoneoffset으로 얻는 것은 무엇입니까? 사실, 미안, 내 실수 ... –

답변

4

시간대 조작이 필요하지 않습니다.

NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]; 
NSString *dateStarted = [NSString stringWithFormat:@"/Date(%.0f)/", interval * 1000]; 

이렇게하면 사용자의 시간대와 상관없이 UTC로 시간이 제공됩니다.

사용해보기. 테스트 장치에서이 코드를 여러 다른 시간대 설정으로 실행하면 모든 경우에서 동일한 결과가 나타납니다.

+0

요점을 놓치고 있습니다. 나는 UTC 날짜 문자열을 만드는 방법을 이해합니다. 하지만 API가 날짜를 처리하는 방식 때문에 UTC 시간을 초 단위로 변경하고 시간대 오프셋을 기준으로 다시 계산해야합니다. 초를 더하거나 뺍니다. 이것은 나의 질문이었다. –

+0

@NicHubbard 그건 말이 안됩니다.모든 서버가해야 할 일은 모든 문자열 값이 UTC이며 아무것도 할 특별한 것이 없다는 것입니다. – rmaddy

+0

API에 버그가있을 때 이것이 필요한 것입니다. –

0
NSDate *currentDate = [NSDate date]; 

지금은 UTC로이 시간을 저장하기 (적어도 아래의 방법을 사용 후), UTC에 (refernce를 날짜 1970 년 이후) 출력 현지 시각

double secsUtc1970 = [[NSDate date]timeIntervalSince1970]; 

날짜 설정 포맷을 사용 :

NSTimeZone *timeZone = [NSTimeZone defaultTimeZone]; 
// or Timezone with specific name like 
// [NSTimeZone timeZoneWithName:@"Europe/Riga"] 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:timeZone]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"]; 
NSString *localDateString = [dateFormatter stringFromDate:currentDate]; 

NSDate 객체는 항상 시간 기준으로 UTC를 사용하지만 날짜의 문자열 표현은 neccessarily UTC 시간대를 기반으로하지 않습니다.

하는 시간대를 얻으려면, 당신은이를 사용할 수 있습니다

전화 할 경우
NSTimeZone* timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
NSString* timeZoneName = [timeZone localizedName:NSTimeZoneNameStyleStandard locale:[NSLocale currentLocale]]; 
NSLog(@"Name : %@", timeZoneName); 

[NSTimeZone abbreviationDictionary] 가능한 모든 약어를 포함하는 사전을 얻을 것이다.

NSLog(@"%@",[NSTimeZone abbreviationDictionary]); 

결과 :이 도움이 될 것입니다

2015-07-10 11:44:05.954 APP[1472:26120] { 
    ADT = "America/Halifax"; 
    AKDT = "America/Juneau"; 
    AKST = "America/Juneau"; 
    ART = "America/Argentina/Buenos_Aires"; 
    AST = "America/Halifax"; 
    BDT = "Asia/Dhaka"; 
    BRST = "America/Sao_Paulo"; 
    BRT = "America/Sao_Paulo"; 
    BST = "Europe/London"; 
    CAT = "Africa/Harare"; 
    CDT = "America/Chicago"; 
    CEST = "Europe/Paris"; 
    CET = "Europe/Paris"; 
    CLST = "America/Santiago"; 
    CLT = "America/Santiago"; 
    COT = "America/Bogota"; 
    CST = "America/Chicago"; 
    EAT = "Africa/Addis_Ababa"; 
    EDT = "America/New_York"; 
    EEST = "Europe/Istanbul"; 
    EET = "Europe/Istanbul"; 
    EST = "America/New_York"; 
    GMT = GMT; 
    GST = "Asia/Dubai"; 
    HKT = "Asia/Hong_Kong"; 
    HST = "Pacific/Honolulu"; 
    ICT = "Asia/Bangkok"; 
    IRST = "Asia/Tehran"; 
    IST = "Asia/Calcutta"; 
    JST = "Asia/Tokyo"; 
    KST = "Asia/Seoul"; 
    MDT = "America/Denver"; 
    MSD = "Europe/Moscow"; 
    MSK = "Europe/Moscow"; 
    MST = "America/Denver"; 
    NZDT = "Pacific/Auckland"; 
    NZST = "Pacific/Auckland"; 
    PDT = "America/Los_Angeles"; 
    PET = "America/Lima"; 
    PHT = "Asia/Manila"; 
    PKT = "Asia/Karachi"; 
    PST = "America/Los_Angeles"; 
    SGT = "Asia/Singapore"; 
    UTC = UTC; 
    WAT = "Africa/Lagos"; 
    WEST = "Europe/Lisbon"; 
    WET = "Europe/Lisbon"; 
    WIT = "Asia/Jakarta"; 
} 

희망.

-1
public let Date_format_Default:String = "yyyy-MM-dd HH:mm:ss" 

설정 UTC 문자열이 형식 문자열;

public let Date_format_Z:String = "yyyy-MM-dd HH:mm:ssZ" 
public let Time_zone_UTC:String = "UTC" 

open class func convertDate2UTC(_ date:String)->(String){ 
    var df_:DateFormatter?=DateFormatter() 
    df_!.dateFormat=Date_format_Z 
    let tz_=TimeZone(identifier: Time_zone_UTC) 
    df_!.timeZone=tz_ 
    let df_s=df_!.date(from: date) 

    df_!.dateFormat=Date_format_Default 
    let string_=df_!.string(from: df_s!) 

    df_ = nil 
    return string_; 
} 
+0

1) OP에는 날짜 문자열이 없으므로이 코드의 요점은 무엇입니까? 2) 왜 대부분을 암시 적으로 결정할 수있을 때 변수 유형을 명시 적으로 설정합니까? 3) 왜''df_''를 옵션으로 만들었습니까? 그 이유는 없으며 코드가 불필요한'! '로 오염 될 수 있습니다. – rmaddy