Search code examples
iosobjective-cswift3nsdateformatter

how do i convert a string to specific format


I have referred lot of links but could not find the solution hence asking it again.I have string which i need to convert into date format. Below is example

Input string : "1410271500" In above string 14 is for 2014

            10 is for Oct

            27 is day

            1500 is 3:00 PM

Output string : "2014-10-27 03:00:00"

Input string in not in long-integer format.

Thanks


Solution

  • do like

    NSString *getMilliSec = @"1410271500";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyMMddHHmm"];
    NSDate *getDate = [formatter dateFromString:getMilliSec];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss a"]; // or use yyyy-MM-dd hh:mm:ss
    formatter.timeZone = [NSTimeZone systemTimeZone]; // optional
    NSString *stringFromDate = [formatter stringFromDate:getDate];
    

    swift3

     let getMilliSec = "1410271500"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyMMddHHmm"
        let getDate = formatter.date(from: getMilliSec)
        formatter.dateFormat = "yyyy-MM-dd hh:mm:ss a" // or use yyyy-MM-dd hh:mm:ss
        formatter.timeZone = NSTimeZone.system // optional
        var stringFromDate = formatter.string(from: getDate!)
    

    output

    enter image description here