Skip to content

Instantly share code, notes, and snippets.

@moyashi
Created March 21, 2010 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moyashi/339164 to your computer and use it in GitHub Desktop.
Save moyashi/339164 to your computer and use it in GitHub Desktop.
#import <sys/time.h>
#define JST_OFFSET 32400
struct timeval tNewTime;
NSURL *poURL = [NSURL URLWithString:@"http://www.google.co.jp/"];
NSMutableURLRequest *poURLReq = [NSMutableURLRequest requestWithURL:poURL];
[poURLReq setHTTPMethod:@"TRACE"];
NSHTTPURLResponse *poURLResp;
NSError *poErr;
[NSURLConnection sendSynchronousRequest:poURLReq
returningResponse:&poURLResp
error:&poErr];
if ( poErr != nil ) {
NSLog(@"結果: アクセスエラー");
return;
} else {
NSLog(@"結果: 時刻取得成功");
}
// 本来はここでリクエスト送信→レスポンス受信までのラグを計測して、後で補正する必要がありますね
// HTTP Responseヘッダを取得する
NSDictionary *poHTTPHeader = [poURLResp allHeaderFields];
//NSLog(@"[poHTTPHeader objectForKey:@\"Date\"]: %@", [poHTTPHeader objectForKey:@"Date"]);
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss 'GMT'"];
// ロケールを設定しておかないと、曜日が日本語になってしまう
[dateForm setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]];
NSDate *newDate = [dateForm dateFromString:[poHTTPHeader objectForKey:@"Date"]];
// JST_OFFSET(32400)とかじゃなくまともなローカルタイムへの変換の仕方があるはず
tNewTime.tv_sec = (long)[newDate timeIntervalSince1970] + JST_OFFSET;
tNewTime.tv_usec = 0;
NSLog(@"timeIntervalSince1970: %d", (long)[newDate timeIntervalSince1970] + JST_OFFSET);
NSLog(@"time(): %d", time(NULL));
NSLog(@"%@", [NSString stringWithFormat:@"誤差: %d 秒", (long)[newDate timeIntervalSince1970] + JST_OFFSET - time(NULL)]);
// システムの時刻設定:ルート権限必要
settimeofday( &tNewTime, NULL );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment