有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java时间戳计算函数

我试图将Java代码作为项目的一部分来编写,以获取进程的当前时间,然后需要为其添加一个固定的超时时间。此新时间必须与我的上述当前时间进行比较,并据此作出决定。我无法将时间添加到当前时间并进行比较。有人能帮我提个建议吗

这是我的代码:

   public class SessionDetails
    {
     public String getCurrentUtcTimestamp() {
        TimeZone timeZone = TimeZone.getTimeZone("UTC:00");
        DateFormat dateFormat = DateFormat.getDateTimeInstance();
        dateFormat.setTimeZone(timeZone);
        timeStamp = dateFormat.format(new Date());
        return timeStamp;
    }
     public void createSession()
         {
           int value = getsession();
           String timeStamp = getCurrentUtcTimestamp() ;
           System.out.println("New session Details :");
           System.out.println("session value:" + value);
           System.out.println("Time of creation :" + timeStamp );
         }
    public boolean checkTimeout(int value)
        {   
            private static long c_Timeout = 10000;
            String currentTime =  getCurrentUtcTimestamp() ;
            if ( currentTime > timeStamp + c_Timeout )   //failing to implement this logic efficiently .please do suggest a way.Thanku..
             System.out.println("Sorry TimeOut");
           else 
             System.out.println("Welcome");

        }
 }

共 (3) 个答案

  1. # 1 楼答案

    您永远不想使用String来存储/处理精确的日期

    通常,您希望使用DateCalendar甚至更现代的Java日期/时间API,如Joda Time或JSR-310reference implementation here

    如果您只是想使用简单的本地时间戳,那么long就足够了:

    long currentTime = System.currentTimeMillis();
    

    long的优点是,您可以像使用任何其他数字基元类型一样使用所有常规操作(加法、减法、相等检查、小于检查)

  2. # 2 楼答案

    只是简单化你的方法返回长

    public long getCurrentUtcTimestamp() 
    {
        TimeZone utc = TimeZone.getTimeZone("UTC");
        Calendar calendar = Calendar.getInstance(utc);
        return calendar.getTimeInMillis();
    }
    
  3. # 3 楼答案

    您真的需要将时间戳存储为字符串吗?我建议使用long,例如调用System.currentTimeMills()的结果。。。然后将其格式化为字符串,仅用于诊断目的。比较long值非常容易:)

    或者,使用Joda Time并将时间戳保留为^{}值。这将使格式化更容易,并且您可以使用isAfterisAfterNow等进行比较