developer tip

문자열을 NSDate로 변환

copycodes 2020. 11. 6. 18:54
반응형

문자열을 NSDate로 변환


NSDateiOS 에서 문자열을로 변환하는 방법은 무엇입니까?


NSString *dateStr = @"20100223";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  

// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];  
[dateFormat release];

이것이 당신을 도울 것입니다.


NSDateFormatter 살펴보고 싶을 것 입니다. 날짜 문자열의 형식을 결정한 다음 dateFromString:문자열을 NSDate 개체로 변환하는 데 사용 합니다.


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/YYYY"];
NSDate *date = [dateFormat dateFromString:dateStr];  
list = [self getYear:date];


- (NSMutableArray *)getYear:(NSDate*)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];

    int year = [components year];
    int month = [components month];
    int day = [components day];
    NSLog(@"%d",year);

    NSMutableDictionary *dateDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d", day], @"day", [NSString stringWithFormat:@"%d", month], @"month", [NSString stringWithFormat:@"%d", year], @"year", nil];

    return dateDict;
}

간단한 방법 당신은 sqlite가 DB를 경우에도 :

// NSTimeInterval is basically typedef of double so you can receive it as double also.
NSTimeInterval *current = [[NSDate date] timeIntervalSince1970]; 
[DB addToDB:current];

//retrieve the date from DB
NSDate *retrievedDateItem = [[NSDate alloc] initWithTimeIntervalSince1970:[getDBValueAsDouble]]; //convert it from double (NSTimeInterval) to NSDate
// Set the style
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// Converted to string
NSString *convertedDate = [dateFormatter stringFromDate:retrievedDateItem];

이 예의 출력 :

2015 년 8 월 3 일 오후 12:27:50


Swift의 내 작업 버전

func dateFor(timeStamp: String) -> NSDate
{
    let formater = NSDateFormatter()
    formater.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy"
    return formater.dateFromString(timeStamp)!
}


func timeStampFor(date: NSDate) -> String
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy"

    return dateFormatter.stringFromDate(date)
}

+(NSDate*)str2date:(NSString*)dateStr{
    if ([dateStr isKindOfClass:[NSDate class]]) {
        return (NSDate*)dateStr;
    }

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    return date;
}

참고 URL : https://stackoverflow.com/questions/2311421/converting-a-string-to-an-nsdate

반응형