2016-10-14 7 views
0

私はたDateFormatterで問題を持っています。私は以下のように私のコードを追加します。最後に文字列とnsdateで同じ日付を取得する方法は?

NSDate *currentDate = [NSDate date]; 
NSLog(@"Current Date: %@",currentDate); //Current Date: 2016-10-14 08:07:15 +0000 

NSTimeZone *timeZone = [NSTimeZone localTimeZone]; 
NSString *tzName = [timeZone name]; 
NSLog(@"Current TimeZone: %@",tzName); //Current TimeZone: Asia/Kolkata 

NSTimeZone *systemTimeZone = [NSTimeZone systemTimeZone]; 
NSString *SyTZName = [systemTimeZone name]; 
NSLog(@"System TimeZone: %@",SyTZName); //System TimeZone: Asia/Kolkata 

NSString *strCurrentDate = [NSString stringWithFormat:@"%@",[NSDate date]]; 
NSLog(@"Current Date: %@",strCurrentDate);//Current Date: 2016-10-14 08:07:47 +0000 

NSDateFormatter* localDateFrm = [[NSDateFormatter alloc] init] ; 
[localDateFrm setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]]; 
[localDateFrm setDateFormat:@"dd-MM-yyyy hh:mm a"]; 
NSString* local_string = [localDateFrm stringFromDate:currentDate]; 
NSLog(@"local_string: %@",local_string);//local_string: 14-10-2016 01:37 PM 

NSDateFormatter* local_dateFormatter = [[NSDateFormatter alloc] init] ; 

[local_dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]]; 
[local_dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"]; 
NSDate *date = [local_dateFormatter dateFromString:local_string]; 
NSLog(@"date : %@",date);//date : 2016-10-14 08:07:00 +0000 

私は01:37 PMを必要とするが、私はその私が回答(1:37 PM)を期待与えないNSDateに文字列を変換.when私は08:07:00 +0000を取得します。時間は違います。 ですので、これを手伝ってください。おかげさまで

+0

'2016年10月14日午前8時07分00秒+ 0000のような通知のためにもtimezoneを設定することができます

2つ目は' 2016年10月14日午前13時37分に等しいです: 00 + 0330'(または-0330、私は決して知らない、NSDateとして)。 – Larme

+1

'NSDate'はGMT形式です(私は思う)、文字列に変換すると変換されるのは – Tj3n

+0

です。それは正しい答えですが、同じ文字列をnsdateに変換するとその文字列が変更されます。実際に私はこのnsdateをUIlocalnotification.firedateに使用する必要があります。 –

答えて

1

NSDateは常に、あなたのローカルタイムゾーンでにそれをしたいならば、あなたはNSDateFormatterstringFromDate方法で文字列に変換する必要があり、utcまたはgmt日付を返します。だから、

、あなただけのstringに変換してから表示され、ローカルタイムゾーンを使用して日付を表示したいです。あなたはNSDateようにそれをしたいとき、そして、あなたは簡単にdateFromString方法で文字列を日付に変換することができ、それが再びutc or gmtで日付を返します。

通常、日付をlabelまたはUIに表示する必要がありますので、文字列が必要な場合は、ラベルにnsdateを表示することはできません。あなたはまた、localnotificationのfiredateとしてこの日付を使用することができます

:だから、これはNSDate

アップデートに対処するための標準的なアプローチです。以下のデモを実行してください

NSString *str = @"2016-10-14 08:07:00"; 

NSDateFormatter *df = [[NSDateFormatter alloc]init]; 
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 

NSDate *date = [df dateFromString:str]; 

NSLog(@"date : %@",[df dateFromString:str]); 


UILocalNotification *notification = [[UILocalNotification alloc]init]; 

notification.fireDate = date; 
notification.alertTitle = @"title"; 

NSLog(@"notification : %@",notification); 

と確認のためにログを確認すると、あなたのローカルタイムゾーンごとに消火時間が表示されます!あなたがする必要があります(NSDateなど)notification.timeZone = ...;

+0

ThxラベルやUIに日付を表​​示する必要がある場合は、文字列だけが必要です。私の問題では、NSlateをUIlocalNotificationで使いたいのでNSdateが必要です。 (UILocalNotification.firedate = [ITSのみがNSDATE NOT STRINGを取る])。 –

+0

答えの更新を確認してください! – Lion

関連する問題