如何从iOS格式化的字符串中获取日期和时间 [英] How to Fetch date and time from a formatted string in iOS

查看:149
本文介绍了如何从iOS格式化的字符串中获取日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSStringdateString,其中包含给定格式的日期和时间。

I have a NSString "dateString" which contains date and time in given format.

MM / dd / yyyy HH:mm: ss a

我想使用 NSDateFormatter 从dateString中获取数据,然后我试图以字符串显示strDate。我可以获取数据,但唯一的问题是我没有得到小时地方的正确值。

I want to fetch the data from the dateString using NSDateFormatter and then I'm trying to show in a String "strDate". I.m able to fetch the data but the only issue is that i'm not getting the correct value for "hour" place.

对于Ex:

dateString   = 1/23/2015 7:06:37 AM
strDate   = 01/23/2015 00:06:37 am

如何解决这个问题。提前致谢。这是我的代码:

How to resolve this issue. Thanks in advance. This is my code:

-(NSString *)getDateQuestion:(NSString *)dateString
{
NSLog(@"dateString   = %@",dateString);

//NSString to NSDate
NSDate          *datefromString  = [[NSDate alloc] init];
NSDateFormatter *dateFormatter   = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5:30"]];
[dateFormatter setTimeZone: [NSTimeZone systemTimeZone]];

[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

datefromString                   = [dateFormatter dateFromString:dateString];
NSLog(@"dateString1   = %@",datefromString);

//NSDate convert to NSString
 [dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5:30"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSString       *strDate          = [dateFormatter stringFromDate:datefromString];
NSLog(@"strDate   = %@",strDate);

return strDate;
}


推荐答案

Just Pass正确日期时间字符串到功能和不设置时区不必要的一次又一次...我希望它可以帮助你...

Just Pass Correct date Time string to the function and don't set time zone Unnecessary again and again... i hope it helps you...

NSDate *dat = [NSDate date];
NSDateFormatter *dateFormatter   = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC+05:30"]];

[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];

NSString * dateString =[dateFormatter stringFromDate:dat];
NSLog(@"dateString   = %@",dateString);
NSLog(@"dateString1   = %@",dateString);

//NSDate convert to NSString
[dateFormatter setDateFormat:@"HH:mm:ss a"];

NSString       *strDate          = [dateFormatter stringFromDate:dat];
NSLog(@"strDate   = %@",strDate);

HH代表24小时。

饱食12小时。

这篇关于如何从iOS格式化的字符串中获取日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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