Objective-C:如何从 Julian 日期字段创建 NSDate

标签 objective-c date julian-date

我创建了一个类别来帮助我处理从年、月、日字段创建日期。我现在还需要从儒略日期 (YYJJJ) 创建日期。我已经解析了 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

这是我的 NSDateCategory:

    #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

关于Objective-C:如何从 Julian 日期字段创建 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549667/

相关文章:

objective-c - 为 UIScrollView 创建大 View 的便捷方法?

ios - 什么定义了 UIScrollView 分页大小?

java - 日期和时区(javascript、java、struts)

date - MM 中的月份在 Hive 中使用 Month()

c# - Julian 时间戳到日期时间

c# - 在 C# 中将 Julian 日期与时间 (H/m/s) 转换为日期时间

iphone - reloadData 没有被调用

objective-c - Storyboard导航

php - 使用 PHP 在 MySQL 中插入和检索日期的正确方法

c++ - 如何计算朱利安算术