如何以am / pm格式获取时间iphone NSDateFormatter? [英] How to get the time in am/pm format iphone NSDateFormatter?

查看:130
本文介绍了如何以am / pm格式获取时间iphone NSDateFormatter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NSDateFormatter在iPhone应用中工作。我从网络服务获得时间,如00:00:00,16:00:00,15:30:00等等。如果时间00:00:00到12 AM,如果时间 >16:00:00至4 PM,如果时间是15:30:00至3.30 PM。我使用了以下代码,但是当我通过16:00:00时,日期返回null

Am working in an iPhone app with using the NSDateFormatter. Am getting the time from the webservice like "00:00:00", "16:00:00","15:30:00" and so on. I need to convert these time to if the time is "00:00:00" to "12 AM", if the time is "16:00:00" to "4 PM", if the time is "15:30:00" to "3.30 PM". I have used the below code to this but when i have pass "16:00:00" the date returns null.

 NSString *dats1 = @"16:00:00";
 NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];  
 [dateFormatter3 setDateFormat:@"hh:mm:ss"]; 
 NSDate *date1 = [dateFormatter3 dateFromString:dats1];
 NSLog(@"date1 : %@", date1); **// Here returning (null)**

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"hh:mm a"];
 NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
 [formatter release];

当通过00:00:00时,它正确地返回12 AM。有谁可以帮我解决这个问题?在此先感谢。

When am passing "00:00:00" it is returning "12 AM" correctly. Can anyone please help me to solve this issue? Thanks in advance.

推荐答案

如果您的时间格式在 24小时,请使用HH:mm:ss格式。请测试代码并告诉我它是否适合您。我已经过测试,它正在返回4 PM

If your time format is in 24hrs please use "HH:mm:ss" format. Please test the code and let me know if it is working for you. I have tested and it is returning "4 PM"

NSString *dats1 = @"16:00:00";
 NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];  
 [dateFormatter3 setDateFormat:@"HH:mm:ss"]; 
 NSDate *date1 = [dateFormatter3 dateFromString:dats1];
 NSLog(@"date1 : %@", date1); **// Here returning (null)**

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"hh:mm a"];
 NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
 [formatter release];

谢谢。

这篇关于如何以am / pm格式获取时间iphone NSDateFormatter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆