开发者

Creating date from string

开发者 https://www.devze.com 2023-02-05 07:48 出处:网络
I am having trouble getting the time for today from a string. I am reading in a time from a UITextField, but the date is coming out as the start of the epoch

I am having trouble getting the time for today from a string. I am reading in a time from a UITextField, but the date is coming out as the start of the epoch

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setDateSty开发者_运维百科le:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setLenient:YES];

NSLog(@"Format: %@",[formatter dateFormat]);    
NSDate *now = [formatter dateFromString:[textbox text]];
NSLog(@"Time from textfield: %@",now]);

This gives the following date from the log code.

2011-01-19 18:56:28.193 MyApp[8284:207] The time for now: 1970-01-01 06:00:00 GMT


Setting the dateStyle and timeStyle for the formatter will override the dateFormat that you have set manually. The following should work as expected:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setLenient:YES];

NSLog(@"Format: %@",[formatter dateFormat]);

[formatter release];

The resulting date object will be close to the start of the epoch because you are not providing a year, month and day. If you want the time in the textfield to represent a time on today's date, you will have to add in some extra code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH-mm"];
[formatter setLenient:YES];
NSDate *time = [formatter dateFromString:[textbox text]];
[formatter release];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:NSYearCalendarUnit |
                                               NSMonthCalendarUnit |
                                               NSDayCalendarUnit |
                                               NSHourCalendarUnit |
                                               NSMinuteCalendarUnit
                                      fromDate:[NSDate date]];
NSDateComponents *timeComps = [calendar components:NSHourCalendarUnit |
                                                   NSMinuteCalendarUnit
                                          fromDate:time];

[comps setHour:[timeComps hour]];
[comps setMinute:[timeComps minute]];
NSDate *date = [calendar dateFromComponents:comps];
NSLog(@"Date from textfield: %@",date);


NSDate *todayDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:todayDate];
NSLog(@"The current time is:%@",currentTime);
[dateFormatter release];
0

精彩评论

暂无评论...
验证码 换一张
取 消