如何将date格式化为IST?

我必须格式化date如下:

19-JUL-2014 10:27:16 IST

我怎样才能做到这一点? 我应该发送“IST”作为string对象吗?

我试过了 –

NSDate* sourceDate = [NSDate date]; NSLog(@"Date is : %@", sourceDate); NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; NSLog(@"TimeZone is : %@", currentTimeZone); NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init] ; dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss Z"]; [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; NSLog(@"%@",[dateFormatter stringFromDate:sourceDate]); 

根据苹果的官方文档和Unicodedate格式化标准,我已经尝试过几种时区格式化程序 。

我像这样引入了时区:

 NSTimeZone *_timezone = [NSTimeZone timeZoneWithName:@"IST"]; 

这给了我+0530偏移给我适当的时区,所以这是用于我的NSDateFormatter的实例。

 NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc]init]; [_dateFormatter setTimeZone:_timezone]; 

这里是我用不同格式scpecifiers经历的列表:

  • z = GMT+0530 IST
  • zz = GMT+0530 IST
  • zzz = GMT+0530 IST
  • zzzz = India Standard Time IST
  • zzzzz = India Standard Time IST

似乎没有一个标准的格式说明符只能提供实际的"IST"作为string,匹配是格式说明符zzzzzzzzz"India Standard Time IST" – 但你可以看到"GMT+0530 IST"仍然包含它与格式化的其余部分。

注:其他格式说明符,如ZvVxX似乎也不是有用的。


我已经阅读了关于格式说明符的更多信息,文档中提到了使用z

短特定的非位置格式 (例如PDT)。 在不可用的地方,可以回到格式化的GMT格式

这意味着对我来说, 印度标准时间的实际短的具体非地点格式不能直接通过NSDateFormatter – 或由于某种原因指定为"GMT+0530 IST"而不是简短的"IST"

另一方面,我不确定您的服务器端是否接受长特定的非位置格式 (又名"India Standard Time IST" ),或者时区只能用string"IST"标记。

恐怕如果预计最新的格式只有你需要手动和不雅的添加,如:

 [_dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss"]; NSString *_date = [[_dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@" IST"]; 

注意:我也发现月份的名字也应该大写,我不确定这是另一个期望或月份名称(如“七月”,“九月”等通用大写)是对于你的服务器端足够好 – 我没有照顾在我目前的答案资本化他们。


†我还没有find任何标准来描述实际的短格式,所以基于unicode标准,我认为"IST"应该是对"GMT+0530 IST"的缩短格式 – 但这是基于我个人的猜测而已。

  NSDate* sourceDate = [NSDate date]; NSLog(@"Date is : %@", sourceDate); NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; NSLog(@"TimeZone is : %@", currentTimeZone); NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init] ; [dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss zzz"]; [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; NSLog(@"%@",[dateFormatter stringFromDate:sourceDate]); 

这可能会帮助你

请试试这个,

 NSDate *date= [NSDate date]; NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; [dateFormatter1 setDateFormat:@"dd-MMM-yyyy HH:mm:ss z"]; NSLog(@"%@",[dateFormatter1 stringFromDate:date]);