如何从日期中获取小时、分钟和上午/下午? [英] How to get the hours,minute and am/pm from a date?

查看:68
本文介绍了如何从日期中获取小时、分钟和上午/下午?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从日期中提取小时、分钟和上午/下午,但我得到了 NULL 输出.我已经在下面展示了我的代码,请查看.

I tried to extract hours,minute and am/pm from date but i am getting NULL output. I have shown below my code, please review it.

NSString *dateStr=@"29/07/2013 02:00am";
NSDateFormatter * formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mmaa"];
NSDate *date=[formatter dateFromString:dateStr];
NSString *finalDate=[formatter stringFromDate:date];
NSLog(@"%@",finalDate);

非常感谢

推荐答案

你已经很接近了,但是你需要在解析它之前指定你的原始字符串是什么日期格式,然后设置你想要的日期格式在创建之前输出:

You are very close, but you need to specify what date format your original string is in before you parse it, and then set the date format that you want the output to be in before you create it:

NSString *dateStr=@"29/07/2013 02:00am";

// Create a date formatter
NSDateFormatter * formatter=[[NSDateFormatter alloc] init];

// As rmaddy pointed out, you should set the locale:
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

// Set the date format for the input string
[formatter setDateFormat:@"dd/MM/yyyy hh:mma"];

// Create the NSDate from the string
NSDate *date=[formatter dateFromString:dateStr];

// Set the date format for the output string
[formatter setDateFormat:@"hh:mma"];

// Create the output string
NSString *finalDate=[formatter stringFromDate:date];
NSLog(@"%@",finalDate);  //  Output is: 02:00AM

这篇关于如何从日期中获取小时、分钟和上午/下午?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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