Objective-C: Как создать NSDATE из полей Джулиана Дата

StackOverflow https://stackoverflow.com/questions/4549667

  •  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 из этих полей?

Редактировать:Вот функциональность в Java, которую я пытаюсь перевести в Objective-C

// 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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top