-1

I want to convert a NSString to a 12Hr DateTime format.

for example : 2013-08-27 13:11:08 convert to : 2013-08-27 01:11:08 format

sneha
  • 7
  • 1
  • 6
  • 1
    possible duplicate of [Convert NSDate to NSString](http://stackoverflow.com/questions/576265/convert-nsdate-to-nsstring) – Rytis I Aug 27 '13 at 10:55
  • Convert NSString to NSDate then back to NSString – Rytis I Aug 27 '13 at 10:56
  • Well, you can either convert to NSDate and back (plenty of examples on the web, using NSDateFormatter), or you can figure out where the hours field is, extract it, and subtract off 12 if it's > 12. – Hot Licks Aug 27 '13 at 11:13

4 Answers4

1

Make an NSDate with

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];  

Then make a NSString with

[dateFormat setDateFormat:@"yyyy-MM-dd hh:mma"];
Rytis I
  • 1,105
  • 8
  • 19
nerowolfe
  • 4,787
  • 3
  • 20
  • 19
0

You can use NSDateFormatter for conversion of date from 24Hr to 12Hr via following code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH:mm";
NSDate *date = [dateFormatter dateFromString:@"15:15"];

dateFormatter.dateFormat = @"hh:mm a";
NSString *pmamDateString = [dateFormatter stringFromDate:date];

Hope this Helps You !

Arpit Kulsreshtha
  • 2,452
  • 2
  • 26
  • 52
  • Thank you,I tried it in this way: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd HH:mma"; NSDate *date = [dateFormatter dateFromString:obj.date]; dateFormatter.dateFormat = @"hh:mm a"; NSString *pmamDateString = [dateFormatter stringFromDate:date]; NSLog(@"date:%@",pmamDateString); NSLog(@"orgDate;%@",date); its returning null and the obj.date value is: 2013-08-27 13:11:08 – sneha Aug 27 '13 at 11:05
  • @user2678084 - You need to deal with two DIFFERENT formats. The first does not have the AM/PM field, and hence should not have the "a". The second needs to use lower-case "hh" and may use the "a" if you wish to have that field generated. – Hot Licks Aug 27 '13 at 11:15
0
    NSDate now =  [NSDate date];  // assign your date to "now"
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"YYYY-MM-dd hh:mm:ss";
    NSString *hrDateString = [dateFormatter stringFromDate:now];

This may help you in solving your problem.

Aswathy Bose
  • 4,279
  • 4
  • 32
  • 44
0
var yourStringDate = "12145068985"
var dateString:NSTimeInterval =  yourStringDate.doubleValue / 1000
var  dateformat : NSDateFormatter = NSDateFormatter()dateformat.setLocalizedDateFormatFromTemplate("EEE, dd MMM yyyy HH:mm:ss zzz")
var stringDate = dateformat.stringFromDate(NSDate(timeIntervalSince1970: dateString))
println(stringDate)
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
sam
  • 31
  • 1