在Objective-C中将字符串转换为日期[重复]

问题描述 投票:-5回答:3

这个问题在这里已有答案:

如何在Objective C中将字符串转换为日期。

我尝试了以下但没有弄清楚。

NSString *str = @"3/2/2018 11:44:32 AM";

NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"MM/d/yyyy h:mm:ss a"];

NSDate *resultDate = [[NSDate alloc] init];

resultDate = [df dateFromString:str];

NSLog(@"result date: %@", resultDate);

result date: 2018-03-02 06:14:32 +0000 ,but i need to get it as 
result date: 3/2/2018 11:44:32 AM
ios objective-c iphone nsdate xcode9
3个回答
1
投票

您正在将字符串解析为Date对象。它由print呈现的方式是因为默认情况下如果打印一个对象,则会打印其description。在Date的情况下,它将始终是您获得的格式。但是日期是正确的。

如果你想以前面的方式呈现它,再次使用相同的dateFormatter并将日期格式化为字符串:

NSLog(@"result date: %@", [df stringFromDate:resultDate]);

UPDATE

如果问题是小时转移,那是由于您使用DateFormatter解析时将使用的当前时区。要解决这个问题,请明确设置日期格式化程序的时区和区域设置,请参阅此示例(swift版本,但您需要在dateFormatter上设置timeZonelocale的那两行):

let dateString = "3/2/2018 11:44:32 AM"

let df = DateFormatter()
df.dateFormat = "MM/d/yyyy h:mm:ss a"

// set the timezone and locale of the dateformatter:
df.timeZone = TimeZone(identifier: "GMT")
df.locale = Locale(identifier: "en_US_POSIX")

let date = df.date(from: dateString)

// now it will print as you expect:
print(date)

0
投票

您的问题与您的应用当前区域设置有关,如果您当前的区域设置是“en_US”,那么您的NSLog(@"result date: %@", resultDate);线将打印

结果日期:星期五3月2日11:44:32 2018


-1
投票

也许,这段代码会帮助你,再次将它转换为Nsstring,检查它的代码

 -(void)DateChange

 {
   NSString *Input_Date =@"3/22/2018 11:44:32 AM";

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

  NSDate * Format_date = [dateFormatter dateFromString:Input_Date];
  [dateFormatter setDateFormat:@"M/d/yyyy hh:mm:ss a"];

   NSString *Change_date = [dateFormatter stringFromDate:Format_date];
   NSLog(@"Final Change Date :-  %@",Change_date);
}



 My Output is :- 
 Final Change Date :- 3/22/2018 11:44:32 AM
© www.soinside.com 2019 - 2024. All rights reserved.