kype
kype

Reputation: 595

Calculate Date/Time from Date.getTime()

Im calculating a transaction ID based on date/time a transaction is called. Hence im converting a Date object to a long num using .getTime(), code as below

public long calcTransactionID (Date myDate)
{
    long transactionID;
    transactionID = myDate.getTime();
    return long;
}

Works perfectly. Now how can i do the reverse, given transaction ID i want to get the Date object (or at least the date/time in a string).

public getDateFromTrans (long transactionID)
{
    ???
    return myDate;
}

Is it possible to construct a date object using Date.getTime()?

Upvotes: 2

Views: 2370

Answers (2)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

You can use a java.util.Calendar too, as:

public void writeDateAndTime(long transactionId) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(transactionId);

    // this is how to get each part
    int year = calendar.get(Calendar.YEAR);
    int month = Calendar.get(Calendar.MONTH);
    int day = Calendar.get(Calendar.DAY_OF_MONTH);
    int hour = Calendar.get(Calendar.HOUR_OF_DAY);
    int minute = Calendar.get(Calendar.MINUTE);
    int second = Calendar.get(Calendar.SECOND);

    // and this is how to get a java.util.Date object
    Date date = Calendar.getTime();
}

Upvotes: 0

Masudul
Masudul

Reputation: 21961

Try:

public Date getDateFromTrans (long transactionID)
{
    return new Date(transactionID);
}

Upvotes: 4

Related Questions