ios - 如何在字符串和 nsdate 中获取相同的日期?

标签 ios objective-c nsdateformatter

我在日期格式化程序中遇到问题。我添加我的代码如下:

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 但我得到 08:07:00 +0000。当我将字符串转换为 NSDate 时它没有给我预期的回复(01下午 37 点)。所以时间不一样了。 所以请帮助我。 谢谢。

最佳答案

NSDate 将始终返回 utcgmt 日期,如果您希望它在本地时区,则需要将其转换为字符串使用 NSDateFormatterstringFromDate 方法。

因此,当您想要显示您本地时区的日期时,只需将其转换为 string 然后显示即可。当您希望将其作为 NSDate 时,您可以使用 dateFromString 方法轻松地将字符串转换为日期,并且它将再次返回 utc 或 gmt 格式的日期。

通常您需要在 label 或任何 UI 中显示日期,因此您必须需要字符串,您不能在 nsdate 上显示标签。所以,这是处理 NSDate

的标准方法

更新:

您也可以将此日期用作 localnotification 的发布日期。执行下面的演示,

  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);

并检查日志中的通知,它将根据您本地的时区显示开火时间!!

第二件事你可以设置 timezone 也用于通知,比如 notification.timeZone = ...;

关于ios - 如何在字符串和 nsdate 中获取相同的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40038166/

相关文章:

objective-c - 自定义按钮的标题

java - 跨平台 iPhone/Android 代码共享

iphone - 在 Objective-C 中分配属性

ios - DataFormatterStyle 没有成员 .mediumStyle

ios - ios中的日期转换问题

ios - 什么 NSDateFormat 是 1991-07-26T05 :45:50. 163

ios - 如何解决: Xcode Archive upload failed with error 22421

iphone - MKPinAnnotationView 上的双选触摸

ios - 如何在 NSMutableArray 中存储 indexPath 时传入节值

objective-c - 类似 AOP 的 Objective-c 结构