将 NSDates 从一个日历转换为另一个 [英] Convert NSDates from one calendar to another

查看:58
本文介绍了将 NSDates 从一个日历转换为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多相同标题的问题,但没有人回答我的问题.我希望能够将表示伊斯兰日历的 NSString 转换为在公历中显示该日期的 NSDate.这是我拥有的代码,但它仍然返回伊斯兰日历中的 NSDate.

There are lots of questions with the same title but none has answered my question. I want to be able to convert a NSString that represents Islamic calendar to a NSDate that displays that date in Gregorian calendar. This is the code that i have but it still returns the NSDate in Islamic Calendar.

- (NSDate*) convertToNSDateFromString : (NSString *)dateString : (NSString *)dateFormat
{
//Format the Calendar
NSDateFormatter *f = [[NSDateFormatter alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
[f setCalendar:gregorian];
[f setDateStyle:NSDateFormatterLongStyle];
[f setDateFormat:dateFormat];

NSDate *date = [f dateFromString:dateString];

return date;
}

推荐答案

NSDate 没有日历.这实际上是代表某个时间的时间戳.尝试阅读一些关于 EPOCH 的内容,以获得更好的理解.

The NSDate does not have a calendar. This is actually a time stamp representing a certain time. Try reading a bit about EPOCH to get a better understanding.

无论如何,NSDate 可以使用 timeIntervalSince1970 为您提供从参考时间开始的持续时间(以秒为单位),这将返回 1.1.1970 UTC 的秒数,这实际上就是全部NSDate 是什么.这意味着根本没有魔法工具可以处理这个对象.

Anyway a NSDate can give you a duration in seconds from a reference time using timeIntervalSince1970 this will return a number of seconds from 1.1.1970 UTC and this is actually all what the NSDate is. That means there are no magic tools to work on this object at all.

在这个对象旁边你需要的是一个日历,一个 NSCalendar 应该可以解决这个问题.此日历可以帮助您转换时间表示法,但不能帮助您转换时间本身.因此,您所能做的就是将时间戳转换为日期的不同表示,或者您可以从日期的某个表示中获取时间戳.为什么会这样是因为大多数时候你可以在地球上找到 24 个地点,由于时区的原因,每个地点都有不同的当前时间......并不是我认为你不知道,只是想解释为什么日期工具如此复杂且难以使用.

What you need beside this object is a calendar, a NSCalendar should do the trick. This calendar can help you convert the time representation but not the time itself. So all you can do with it is to convert a time stamp to a different representation of the date or you can get a time stamp from a certain representation of the date. Why this is so is because most of the time you can find 24 locations on earth where each of them have a different current time due to the time zone... It is not that I think you do not know this, just trying to explain why date tools are so complex and hard to use.

这篇关于将 NSDates 从一个日历转换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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