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开发者_Go百科 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.
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.
Use the number of days since the beginning of the year.
new Date().getTime()
The number of milliseconds since 1970 should be unique to each date. Just convert the string to a date object and use getTime()
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.format( myInput );
Use unix timestamp see java.util.Date.getTime()
If you just need a unique key, Calendar's hashCode() should do the trick.
Alternately, you can concatenate the two digit month and day, and four digit year.
Update: the OP clarified the question to want a unique value in the range 1-364. In that case I would convert the date into a Calendar
object and call get (Calendar.DAY_OF_YEAR)
on it - this will return the number of the day within the year, which is exactly what the OP is after it seems.
Original answer:
There about as many ways to do this as there are bits of string. If you want to be able to use the unique numbers for relative comparison of dates then the most obvious solution is to do what most computers do anyway, namely convert the date into some lowest common denominator, like the number of seconds from a particular epoch. Java provides ways for doing this with both the Date
and Calendar
classes. If you only care about days and months, you could achieve the same with something like int v = (month * 120) + day
. If you don't care about comparisons and just want a unique value, you could come up with a digest of the date using a hashing algorithm of some kind. In Java you could, for example, take a String
representation of the date and call hashCode()
on it.
精彩评论