ios 如何在Objective-c中将日期格式设置为24小时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15492601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:46:58  来源:igfitidea点击:

How to set date format to 24 hour in Objective-c?

iosnsdateformatter

提问by Manish Verma

I am having problem displaying proper date in my app. When user sets 24 hour format 'ON' in his date time preferences..my app shows correct time but when 24 hour format is set to 'OFF' it shows nothing.

我在我的应用程序中显示正确的日期时遇到问题。当用户在他的日期时间首选项中将 24 小时格式设置为“ON”时......我的应用程序显示正确的时间,但是当 24 小时格式设置为“OFF”时,它什么也不显示。

Here is the code I am using:

这是我正在使用的代码:

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

[formatter setDateStyle:style];

[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
 NSDate *temp            =   [formatter dateFromString:strDate];

[formatter setDateFormat:format];
[formatter setLocale:[NSLocale currentLocale]];

NSString *returnStr     =   [formatter stringFromDate: temp];
[formatter release];
NSLog(@"Return: %@", returnStr);

return returnStr;

回答by Lithu T.V

Try this

尝试这个

[dateFormat setDateFormat:@"hh:mm:ss"];

HH: 24 hour format

HH:24 小时制

hh: 12 hour format

hh: 12 小时制

So in your case

所以在你的情况下

//after conversion to date

if ON
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

if OFF
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];

回答by Rajesh Loganathan

Very simple try this:

很简单试试这个:

For 12 Hrs :(hh:mm:ss)

12 小时 :(hh:mm:ss)

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss"];

For 24 Hrs :(HH:mm:ss)

24 小时 :(HH:mm:ss)

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

回答by KDeogharkar

use this:

用这个:

Objective-C :

目标-C:

dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

Swift 4.1

斯威夫特 4.1

dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

after that your date won't modified.

之后你的日期不会修改。

回答by Xcoder

Set the locale of the dateFormatter as following. It should sove your problem.

如下设置 dateFormatter 的语言环境。它应该可以解决您的问题。

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
[dateFormatter setLocale:locale];

回答by Kerstin

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm"]; 
NSString *dateString = [dateFormat stringFromDate:[NSDate date]];