简体   繁体   English

从Date.getTime()计算日期/时间

[英]Calculate Date/Time from Date.getTime()

Im calculating a transaction ID based on date/time a transaction is called. 我根据交易的日期/时间计算交易ID。 Hence im converting a Date object to a long num using .getTime(), code as below 因此,我使用.getTime()将Date对象转换为长整数,代码如下

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). 现在,如果要获取给定的交易ID,我该如何做相反的操作:我想获取Date对象(或至少是字符串中的日期/时间)。

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

Is it possible to construct a date object using Date.getTime()? 是否可以使用Date.getTime()构造日期对象?

Try: 尝试:

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

You can use a java.util.Calendar too, as: 您也可以将java.util.Calendar用作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM