سؤال

NSDate *date = [NSDate date];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"hh:mm a"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setLocale:[NSLocale systemLocale]];
NSLog(@" >> %@ >>> %@",date,[df dateFromString:@"12:18 AM"])

And log is

>> 2014-04-10 07:00:48 +0000 >>> 2000-01-01 06:52:00 +0000

I want that the second date has also the same date as the first.

like

  2014-04-10 07:00:48 +0000 >>> 2014-04-10 06:52:00 +0000
هل كانت مفيدة؟

المحلول

If you want to convert the time string "12:18 AM" to a date for the current day then you can proceed as follows:

NSString *time = @"12:18 AM";

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

// Get year-month-day for today:
[fmt setDateFormat:@"yyyy-MM-dd "];
NSString *todayString = [fmt stringFromDate:[NSDate date]];

// Append the given time:
NSString *todaysTime = [todayString stringByAppendingString:time];

// Convert date+time string back to NSDate:
[fmt setDateFormat:@"yyyy-MM-dd h:mm a"];
NSDate *date = [fmt dateFromString:todaysTime];

نصائح أخرى

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];

By using this formatter, you can get NSDate

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top