Problem in setting nsdate value from a string
NSDate *My_StartDate,*My_EndDate ;
NSDateFormatter * df= [[NSDateFormatter alloc]init];
[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
My_StartDate = [df dateFromString:@"01/05/2010 10:15:33"];
My_EndDate = [df dateFromString:@"01/05/2010 10:45:33"];
NSLog(@"%@",My_StartDate);
NSLog(@"%@",My_EndDa开发者_如何学Gote);
In the log i get something like this for the my_startdate as 2010-05-01 04:45:33 +0000 and end date as 2010-05-01 05:15:33 +0000 instead i should have got value as for start date as 2010-05-01 10:15:33 +0000 and end date as 2010-05-01 10:45:33 +0000
Try with below function:
-(NSString *)getDateStringFromDate :(NSDate *)dateValue{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setTimeStyle:NSDateFormatterShortStyle];
[timeFormat setDateFormat:@"HH:mm:ss"];
//[timeFormat setDateFormat:@"HH:mm"];
//[timeFormat setDateFormat:@"HH:mm a"];
////
NSString *theDate = [dateFormat stringFromDate:dateValue];
NSString *theTime = [timeFormat stringFromDate:dateValue];
NSLog(@"\n"
"theDate: |%@| \n"
"theTime: |%@| \n"
, theDate, theTime);
return theDate;
}
Change Format of data as per your need.
Let me know in case of any difficulty.
Cheers.
This shows date which follow American standard time string but by this reason you don't get any problem in making your logic.Also
[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
this format using 12 hour format (means 2:03 pm and 2:03 am) and date object never use am and pm for showing date object value but when you convert it correctly then it gives you right date and time.
If you feel you get any problem then use different locale for that.
It is displaying asper the GMT+4.30 time.It displays like that only.When you are converting that date to string using the DateFormatter it gives the same date(Whichever you want like start date as 01/05/2010 10:15:33 and end date as 01/05/2010 10:45:33).
NSDateFormatter * dateformatter= [[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
NSString *dat = [dateformatter stringfromDate:My_StartDate];
then you will get the output as 01/05/2010 10:15:33
You might want to set the time zone of the date formatter to GMT
here. Do it using
[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
before you do dateFromString:
calls. This will give you what you want.
Just need to update here in your code:
I might be like that your time would be in 24 hours format, so at that time you need to use this ....other than that you need to set the timezone.
Follow this link for All zone : http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns
[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
to
[df setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
You are Done ;)
精彩评论