Objective-C:ジュリアンデートフィールドからNSDateを作成する方法
-
13-10-2019 - |
質問
年、月、日のフィールドからの日付の作成に対処するのに役立つカテゴリを作成しました。また、ジュリアンデート(YYJJJ)から日付を作成する必要があります。ジュリアンデートの文字列を解析しましたが、今は持っています
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
所属していません StackOverflow