问题
I have a date string of
"5:09 pm Wed Sep 2",which is coming from server.
when converting the string into NSDate
.
"2000-09-02 17:09:00 +0000" but the year should have been "2015" like:
"2015-09-02 17:09:00 +0000"
Here is my code please let me know where is the problem
NSString *dateStr = @"5:09 pm Wed Sep 2";
// Convert string to date object
NSString *dateFormat= ([self hasAMPM])?@"hh:mm a EEEE MMM d":@"hh:mm a EEEE MMM d" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateStr OutputFormat:dateFormat]];
///****
-(BOOL)hasAMPM{
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:@"a"];
BOOL hasAMPM = containsA.location != NSNotFound;
return hasAMPM;
}
-(NSDate *)toLocalTime:(NSDate *)date
{
NSTimeZone *tz = [NSTimeZone systemTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: date];
return [NSDate dateWithTimeInterval: seconds sinceDate: date];
}
-(NSDate *)convertDateFromString:(NSString *)strDate OutputFormat:(NSString *)outPutFormat
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:outPutFormat];
NSDate *date1= [formatter dateFromString:strDate];
return date1;
}
Please help me to get out of this situation.
回答1:
If you want to add the year in your date according to current date, this works for dates from 1970 onwards, haven't checked for beyond that:
NSString *dateStr = @"5:09 pm Wed Sep 2";
NSString *dateString = [dateStr stringByAppendingString:@" 1970"];
// Convert string to date object
NSString *dateFormat= ([self hasAMPM])?@"hh:mm a EE MMM d yyyy":@"hh:mm a EE MMM d yyyy" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateString OutputFormat:dateFormat]];
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
greCalendar.timeZone = [NSTimeZone systemTimeZone];
NSDateComponents *componenetsForCurrent = [greCalendar componentsInTimeZone:[NSTimeZone systemTimeZone] fromDate:[NSDate date]];
NSInteger year = componenetsForCurrent.year;
NSDate *requiredDate = [greCalendar dateByAddingUnit:NSCalendarUnitYear value:(year-1970) toDate:date options:NSCalendarWrapComponents];
回答2:
You can split your date using NSDateComponents, and work with year independently
NSDateComponents *dateComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
[dateComponents setYear:someYear];
date = [calendar dateFromComponents:dateComponents];
来源:https://stackoverflow.com/questions/32352451/a-date-string-without-year-to-nsdate-with-year