Objective c 目标C:如何从Julian日期字段创建NSDate
我创建了一个类别来帮助我处理从年、月、日字段创建日期的问题。我现在还需要根据朱利安日期(YYJJ)创建一个日期。我已经解析了我的Julian日期字符串,现在Objective c 目标C:如何从Julian日期字段创建NSDate,objective-c,date,julian-date,Objective C,Date,Julian Date,我创建了一个类别来帮助我处理从年、月、日字段创建日期的问题。我现在还需要根据朱利安日期(YYJJ)创建一个日期。我已经解析了我的Julian日期字符串,现在 int years // representing the year parsed from the julian date string int days // representing the day of the year parsed from julian date string 这是我的分类: #import "N
int years // representing the year parsed from the julian date string
int days // representing the day of the year parsed from julian date string
这是我的分类:
#import "NSDateCategory.h"
@implementation NSDate (MBDateCat)
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
return [calendar dateFromComponents:components];
}
@end
如何从这些字段创建NSDate
编辑:
下面是我试图翻译成Objective-C的Java功能
// Julian Exp Date
// (YYJJJ)
Date dt = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int years = new Integer(mid(data, 0, 2)).intValue();
int days = new Integer(mid(data, 2, 3)).intValue();
int year = ((cal.get(Calendar.YEAR) / 20) * 20) + years;
int month = 0;
int day = 0;
cal.set(year, month, day);
cal.add(Calendar.DAY_OF_YEAR, days);
myData.setDate(cal);
使用
NSDateFormatter
,给定正确的格式字符串,它可以实现您想要的:
NSString *dateString = @"10123"; // 123. day of 2010
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyDDD"];
NSDate *aDate = [fmt dateFromString:dateString];
[fmt release];
NSLog(@"Date: %@", aDate);
这将返回:
Date: 2010-05-03 00:00:00 +0200
我认为这不能正确地转换年份值。请参阅我添加到问题中的示例java代码——它使用int数学技巧来确定年份。请参阅我更新的示例。这对我来说是可行的,但我还不习惯Julian years,也许这对你来说确实失败了。最后,我进行了单元测试,测试了这段代码,它确实正确地解析了日期。Thank.tia,仅仅因为您正在转换java方法,您就不必将它转换为obj-C。Pascal编写的答案就可以了。