简体   繁体   English

如何从iOS中的格式化字符串中获取日期和时间

[英]How to Fetch date and time from a formatted string in iOS

I have a NSString "dateString" which contains date and time in given format. 我有一个NSString“ dateString”,其中包含给定格式的日期和时间。

"MM/dd/yyyy HH:mm:ss a" . "MM/dd/yyyy HH:mm:ss a"

I want to fetch the data from the dateString using NSDateFormatter and then I'm trying to show in a String "strDate" . 我想使用NSDateFormatter从dateString提取数据,然后尝试在字符串"strDate" Im able to fetch the data but the only issue is that i'm not getting the correct value for "hour" place. 我无法获取数据,但唯一的问题是我没有获得"hour"位置的正确值。

For 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 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 stands for 24hr. HH代表24小时。

hh satnds for 12 hr. ……坐了12个小时。

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

替换为"MM/dd/yyyy hh:mm:ss a"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM