当电话日历不是公历时,如何以公历格式获取今天的日期? [英] How to get today's date in the Gregorian format when phone calendar is non-Gregorian?

查看:93
本文介绍了当电话日历不是公历时,如何以公历格式获取今天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

给出当前日期.

但是,如果手机日历不是公历(在模拟器上也有日文和佛历),则当前日期不会是公历.

However if the phone calendar is not Gregorian (on the emulator there is also Japanese and Buddhist), the current date will not be Gregorian.

现在的问题是如何转换为公历日期或确保它从一开始就是公历格式.这对于某些服务器通信至关重要.

The question now is how to convert to a Gregorian date or make sure it will be in the Gregorian format from the beginning. This is crucial for some server communication.

谢谢!

推荐答案

NSDate 只代表一个时间点,本身没有格式.

NSDate just represents a point in time and has no format in itself.

将 NSDate 格式化为例如一个字符串,你应该使用 NSDateFormatter.它有一个日历属性,如果您将此属性设置为公历的实例,则输出的格式将匹配公历样式.

To format an NSDate to e.g. a string, you should use NSDateFormatter. It has a calendar property, and if you set this property to an instance of a Gregorian calendar, the outputted format will match a Gregorian style.

NSDate *now = [NSDate date];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:gregorianCalendar];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];

NSString *formattedDate = [formatter stringFromDate:now];

NSLog(@"%@", formattedDate);

[gregorianCalendar release];
[formatter release];

这篇关于当电话日历不是公历时,如何以公历格式获取今天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆