Convert JavaUtilDate to NSDate and vice versa?

845 views Asked by At

I use j2objc to translate a java util Date to a objective-c JavaUtilDate class. I imported #import "java/util/Date.h"to store a translated java Date variable.

var myDate: JavaUtilDate

How do I convert a JavaUtilDate into an NSDate?

1

There are 1 answers

7
BlakeP On

Depending on where/how you get the Java Date, your best bet would be to get the milliseconds and instantiate the NSDate with it.

So call the getTime() method on the Java Date to get milliseconds since Epoch, then create your NSDate with the dateWithTimeIntervalSince1970: method. The NSDate method takes seconds (as a floating point), so divide by 1000.0 to keep the precision (thanks to Martin R for pointing this out in comments). :)

Java Util Date method

NSDate method


There seems to be some confusion on what exactly is being asked. To be as general as possible, time objects typically have a method to get the milliseconds since epoch and a constructor (or setter) to pass in the seconds since epoch. So all you have to do is get the seconds from one object and instantiate the other object with the seconds.