3

I've created a category to help me deal with creating dates from year, month, day fields. I now also have the need to create a date from a Julian Date (YYJJJ). I've parsed my Julian date string and now have

int years  // representing the year parsed from the julian date string
int days  // representing the day of the year parsed from julian date string

here is my 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

How do I create an NSDate from these fields?

Edit: Here is the functionality in Java that I am trying to translate into 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);
tia
  • 1,004
  • 3
  • 16
  • 21
  • tia, just because you are converting a java method you don't have to convert it line my line to obj-C. The answer written by Pascal will work. – Black Frog Jan 03 '11 at 18:13

1 Answers1

3

Use NSDateFormatter, given the right format string it achieves what you want:

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);

This returns:

Date: 2010-05-03 00:00:00 +0200
Pascal
  • 16,846
  • 4
  • 60
  • 69
  • I don't think this will translate the year value correctly. See the sample java code that I added to my question - it's using an int math trick to determine the year. – tia Dec 28 '10 at 23:28
  • See my updated example. It works for me, but I'm not used to Julian years, maybe this indeed fails for you. – Pascal Dec 29 '10 at 11:56
  • finally got to the unit tests exercising this code and it indeed parses the date correctly. thanks. – tia Jan 03 '11 at 20:44