Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique int from Date

This is general programming, but I'm working in Java.

Given a date dd-mm-yy or dd-mm-yyyy (e.g. 13-01-2011) I want to convert this into a unique number such that any two dates have a different number. And the year isin't important. So just converting dd-mm into one unique int is acceptable. Does anyone know an algorithm for doing this?

I'm SOrry: I want to be more specific:

The unique numbers should be from 1 to 365 (or 0 to 364), or should break down uniquely modulo 365. (I'm ignoring the case of leap years at the moment).

So concatenating "ddmm" might be a unique 4 digit number. But modulo 365 probably wouldnt be unique.


1 Answers

So you basically want to get the day of year? That's not the same as "an unique int from date".

Use Calendar#get(Calendar.DAY_OF_YEAR) (which is 1-based).

Date date = getItSomehow();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);

As you already admitted, comparing this on leap/non-leap years will fail.

like image 63
BalusC Avatar answered May 09 '26 14:05

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!