【问题标题】:How to convert TimeStamp to Date in Java?如何在 Java 中将时间戳转换为日期?
【发布时间】:2012-08-04 01:42:42
【问题描述】:

在java中获得计数后如何将'timeStamp'转换为date

我目前的代码如下:

public class GetCurrentDateTime {

    public int data() {
        int count = 0;
        java.sql.Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
        java.sql.Date date = new java.sql.Date(timeStamp.getTime()); 
        System.out.println(date);
        //count++;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro", "root", "");

            PreparedStatement statement = con.prepareStatement("select * from orders where status='Q' AND date=CURDATE()");
            ResultSet result = statement.executeQuery();
            while (result.next()) {
                // Do something with the row returned.
                count++; //if the first col is a count.
            }
        } catch (Exception exc) {
            System.out.println(exc.getMessage());
        }

        return count;
    }
}

这是我的数据库:

这里我得到的输出是 2012-08-07 0,但等效查询返回 3。为什么我得到 0?

【问题讨论】:

标签: java date jdbc timestamp


【解决方案1】:

只需使用邮票的getTime() 值作为参数创建一个新的Date 对象。

这是一个示例(我使用当前时间的示例时间戳):

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);

【讨论】:

【解决方案2】:
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );

// Date to timestamp
long timestamp = d.getTime();

//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();

【讨论】:

  • 为什么要乘以 1000?
  • 因为日期的初始化是以毫秒为单位的,而时间戳是以秒为单位的!同样的想法对于所有其他转换!好吃吗?
【解决方案3】:

只是:

Timestamp timestamp = new Timestamp(long);
Date date = new Date(timestamp.getTime());

【讨论】:

    【解决方案4】:

    这个我找了很久,原来Eposh converter很容易做到:

    long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000;
    

    或者相反:

    String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
    

    【讨论】:

      【解决方案5】:

      tl;博士

      LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
          .atStartOfDay( ZoneId.of( "Africa/Tunis" ) )
          .toEpochSecond()
      

      LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
          .plusDays( 1 )
          .atStartOfDay( ZoneId.of( "Africa/Tunis" ) )
          .toEpochSecond()
      

      "SELECT * FROM orders WHERE placed >= ? AND placed < ? ; "
      

      myPreparedStatement.setObject( 1 , start )
      myPreparedStatement.setObject( 2 , stop )
      

      java.time

      您正在使用麻烦的旧日期时间类,这些类现在是遗留的,被现代 java.time 类所取代。

      显然,您将时刻存储在数据库中某个整数类型的列中。那是不幸的。相反,您应该使用诸如 SQL 标准 TIMESTAMP WITH TIME ZONE 之类的类型的列。但是,对于这个答案,我们将使用我们所拥有的。

      如果您的记录表示以毫秒为分辨率的时刻,并且您想要一整天的所有记录,那么我们需要一个时间范围。我们必须有一个开始时刻和一个停止时刻。您的查询只有一个日期时间标准,而它应该有一对。

      LocalDate 类表示没有时间和时区的仅日期值。

      时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,Paris France 中午夜后几分钟是新的一天,而 Montréal Québec 中仍然是“昨天”。

      如果没有指定时区,JVM 会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。

      continent/region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

      ZoneId z = ZoneId.of( "America/Montreal" ) ;  
      LocalDate today = LocalDate.now( z ) ;
      

      如果你想使用 JVM 当前的默认时区,请求它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为默认值可能会在任何时候在运行时被 JVM 中任何应用程序的任何线程中的任何代码更改。

      ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
      

      或者指定一个日期。您可以通过数字设置月份,1 月至 12 月的编号为 1-12。

      LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
      

      或者,更好的是,使用预定义的Month 枚举对象,一年中的每个月一个。提示:在整个代码库中使用这些 Month 对象,而不是仅仅使用整数,以使您的代码更具自记录性、确保有效值并提供 type-safety

      LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
      

      有了LocalDate,接下来我们需要将其转换为一对时刻,即一天的开始和结束。不要假设一天从一天中的 00:00:00 开始。由于夏令时 (DST) 等异常情况,一天可能会从另一个时间开始,例如 01:00:00。所以让 java.time 确定一天中的第一个时刻。我们将ZoneId 参数传递给LocalDate::atStartOfDay 以查找任何此类异常。结果是ZonedDateTime

      ZonedDateTime zdtStart = ld.atStartOfDay( z ) ;
      

      通常,定义时间跨度的最佳方法是半开放方法,其中开始是包含,而结尾是排除。因此,一天从第一刻开始,一直持续到但不包括第二天的第一刻。

      ZonedDateTime zdtStop = ld.plusDays( 1 ).atStartOfDay( z ) ;  // Determine the following date, and ask for the first moment of that day.
      

      我们一整天的查询不能使用 SQL 命令BETWEEN。该命令是完全关闭的([])(包括开头和结尾),而我们想要半开([))。我们使用一对标准 &gt;=&lt;

      您的专栏名称不正确。避免各种数据库保留的千字中的任何一个。我们在这个例子中使用placed

      您的代码应该使用 ? 占位符来指定我们的时刻。

      String sql = "SELECT * FROM orders WHERE placed >= ? AND placed < ? ; " ;
      

      但是我们手头有ZonedDateTime 对象,而您的数据库显然正在存储如上所述的整数。如果您已经正确定义了列,我们可以简单地使用任何支持 JDBC 4.2 或更高版本的 JDBC 驱动程序传递 ZonedDateTime 对象。

      但相反,我们需要在整秒内获得一个从 epoch 开始的计数。我假设您的纪元参考日期是 1970 年 UTC 的第一刻。请注意可能的数据丢失,因为ZonedDateTime 类能够达到纳秒级分辨率。以下行中的任何小数秒都将被截断。

      long start = zdtStart().toEpochSecond() ;  // Transform to a count of whole seconds since 1970-01-01T00:00:00Z.
      long stop = zdtStop().toEpochSecond() ; 
      

      现在我们准备将这些整数传递给上面定义的 SQL 代码。

      PreparedStatement ps = con.prepareStatement( sql );
      ps.setObject( 1 , start ) ;
      ps.setObject( 2 , stop ) ;
      ResultSet rs = ps.executeQuery();
      

      当您从 ResultSet 检索整数值时,您可以转换为 Instant 对象(始终采用 UTC),或转换为 ZonedDateTime 对象(具有指定的时区)。

      Instant instant = rs.getObject( … , Instant.class ) ;
      ZonedDateTime zdt = instant.atZone( z ) ;
      

      关于java.time

      java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

      Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

      要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

      从哪里获得 java.time 类?

      ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

      【讨论】:

        【解决方案6】:

        尝试使用这个java代码:

        Timestamp stamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(stamp.getTime());
        DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat f1 = new SimpleDateFormat("yyyy/MM/dd");
        String d = f.format(date);
        String d1 = f1.format(date);
        System.out.println(d);
        System.out.println(d1);
        

        【讨论】:

          【解决方案7】:

          首先,您没有利用PreparedStatement 的优势。我首先建议你修改你的PreparedStatement如下:

          PreparedStatement statement = con.prepareStatement("select * from orders where status=? AND date=?")
          

          然后您可以使用statement.setXX(param_index, param_value) 设置相应的值。要转换为 timestamp,请查看以下 javadocs:

          PreparedStatement.setTimeStamp()
          Timestamp

          希望这会有所帮助!

          【讨论】:

            【解决方案8】:

            在 Android 中它非常简单。只需使用 Calender 类来获取 currentTimeMillis。

            Timestamp stamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
            Date date = new Date(stamp.getTime());
            Log.d("Current date Time is   "  +date.toString());
            

            在 Java 中只需使用 System.currentTimeMillis() 获取当前时间戳

            【讨论】:

              【解决方案9】:

              不确定您要在查询中选择什么,但请记住,不带参数的 UNIX_TIMESTAMP() 现在返回时间。您可能应该提供一个有效时间作为参数,或者更改条件。

              编辑:

              下面是一个基于问题的限时查询示例:

              PreparedStatement statement = con
                      .prepareStatement("select * from orders where status='Q' AND date > ?");
              Date date = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2000");
              statement.setDate(1, new java.sql.Date(date.getTime()));
              

              编辑:时间戳列

              如果是时间戳使用java.sql.TimestampPreparedStatement.setTimestamp(),即:

              PreparedStatement statement = con
                      .prepareStatement("select * from orders where status='Q' AND date > ?");
              Date date = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2000");
              Timestamp timestamp = new Timestamp(date.getTime());
              statement.setTimestamp(1, timestamp);
              

              【讨论】:

              • 现在我的条件是 select * from xcart_orders where status='Q' AND date=CURDATE()。现在也只显示零
              • @krishnaveni 您要选择哪些记录?
              • date(11111111,123456767,122333344) 和 status=(Q,Q,Q)..all 都保存在我的数据库中。现在我希望需要检查查询并获取计数值并显示在我的控制台上(即)返回计数值后匹配多少数据
              • @krishnaveni 如果您希望结果集受某个日期的约束,则在查询中使用该日期,否则删除日期条件。
              • 当日期以 yyyy-mm-dd 格式保存在我的数据库中时,我的代码中的 可以成功运行。但现在我的日期以 1343469690 格式保存在时间戳中。如何获取计数值?我这里怎么写代码
              【解决方案10】:

              new Date(timestamp.getTime()) 应该可以工作,但新奇的 Java 8 方式(可能更优雅、类型更安全,以及帮助引导您使用新的时间类)是调用Date.from(timestamp.toInstant())

              (不要依赖Timestamp 本身是Date 的实例这一事实;请参阅another answer 的cmets 中的解释。)

              【讨论】:

                【解决方案11】:
                    Timestamp tsp = new Timestamp(System.currentTimeMillis());
                   java.util.Date dateformat = new java.util.Date(tsp.getTime());
                

                【讨论】:

                  【解决方案12】:

                  我觉得有必要做出回应,因为其他答案似乎与时区无关,而现实世界的应用程序无法承受。当时间戳和 JVM 使用不同的时区时,要使时间戳到日期的转换正确,您可以像这样使用 Joda Time 的 LocalDateTime(或 Java8 中的 LocalDateTime):

                  Timestamp timestamp = resultSet.getTimestamp("time_column");
                  LocalDateTime localDateTime = new LocalDateTime(timestamp);
                  Date trueDate = localDateTime.toDate(DateTimeZone.UTC.toTimeZone());
                  

                  以下示例假定时间戳为 UTC(数据库通常是这种情况)。如果您的时间戳位于不同的时区,请更改toDatestatement 的时区参数。

                  【讨论】:

                    【解决方案13】:

                    假设你有一个预先存在的java.util.Date date

                    Timestamp timestamp = new Timestamp(long);
                    date.setTime( l_timestamp.getTime() );
                    

                    【讨论】:

                      【解决方案14】:

                      您可以使用此方法从特定区域的时间戳和时区获取日期。

                      public String getDayOfTimestamp(long yourLinuxTimestamp, String timeZone) {
                          Calendar cal = Calendar.getInstance();
                          cal.setTimeInMillis(yourLinuxTimestamp * 1000);
                          cal.setTimeZone(TimeZone.getTimeZone(timeZone));
                          Date date = cal.getTime();
                      }
                      

                      【讨论】:

                        【解决方案15】:
                        String timestamp="";
                        Date temp=null;
                        try {
                            temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDateCurrentTimeZone(Long.parseLong(timestamp)));
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        int dayMonth=temp.getDate();
                        int dayWeek=temp.getDay();
                        int hour=temp.getHours();
                        int minute=temp.getMinutes();
                        int month=temp.getMonth()+1;
                        int year=temp.getYear()+1900;
                        

                        【讨论】:

                          【解决方案16】:
                          DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                          Date fecha = getDateInTimestamp(); 
                          

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 2012-08-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2014-05-16
                            • 2014-12-03
                            • 1970-01-01
                            • 2017-04-18
                            • 1970-01-01
                            相关资源
                            最近更新 更多