在 java 中将时间戳字符串转换为长字符串

Convert timestamp string to long in java

我必须从数据库中获取时间戳并只检索时间并比较两个时间。

//下面是字符串值

 String st1 = "2015-07-24T09:39:14.000Z";      
 String st2 = "2015-07-24T09:45:44.000Z";

//只检索时间 09:39:14

 String s = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));

//字符串到长。

 Long time = Long.parseLong(s);

 Long tim1=Long.valueOf(s).longValue();

错误:

java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)

试试这个方法,示例代码:

java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2015-07-24T09:45:44.000Z");
long tsTime2 = ts2.getTime();

最简单的解决方案是使用 Java 8 的 Date/Time API

LocalDateTime from = LocalDateTime.parse("2015-07-24T09:39:14.000Z", DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime to = LocalDateTime.parse("2015-07-24T09:45:44.000Z", DateTimeFormatter.ISO_DATE_TIME);
System.out.println(from + " - " + to);

LocalTime fromTime = from.toLocalTime();
LocalTime toTime = to.toLocalTime();

System.out.println(fromTime + " - " + toTime);

System.out.println(fromTime + " before " + toTime + " = " + fromTime.isBefore(toTime));
System.out.println(fromTime + " after " + toTime + " = " + fromTime.isAfter(toTime));
System.out.println(fromTime + " equals " + toTime + " = " + fromTime.equals(toTime));
System.out.println(fromTime + " compareTo " + toTime + " = " + fromTime.compareTo(toTime));

输出

2015-07-24T09:39:14 - 2015-07-24T09:45:44
09:39:14 - 09:45:44
09:39:14 before 09:45:44 = true
09:39:14 after 09:45:44 = false
09:39:14 equals 09:45:44 = false
09:39:14 compareTo 09:45:44 = -1

如果您不使用 Java 8,则使用 Joda-Time,其工作方式类似

Joda-Time 示例...

import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.format.ISODateTimeFormat;

public class JodaTimeTest {

    public static void main(String[] args) {
        LocalDateTime from = LocalDateTime.parse("2015-07-24T09:39:14.000Z", ISODateTimeFormat.dateTime());
        LocalDateTime to = LocalDateTime.parse("2015-07-24T09:45:44.000Z", ISODateTimeFormat.dateTime());

        LocalTime fromTime = from.toLocalTime();
        LocalTime toTime = to.toLocalTime();

        System.out.println(fromTime + " - " + toTime);

        System.out.println(fromTime + " before " + toTime + " = " + fromTime.isBefore(toTime));
        System.out.println(fromTime + " after " + toTime + " = " + fromTime.isAfter(toTime));
        System.out.println(fromTime + " equals " + toTime + " = " + fromTime.equals(toTime));
        System.out.println(fromTime + " compareTo " + toTime + " = " + fromTime.compareTo(toTime));
    }

}

输出

09:39:14.000 - 09:45:44.000
09:39:14.000 before 09:45:44.000 = true
09:39:14.000 after 09:45:44.000 = false
09:39:14.000 equals 09:45:44.000 = false
09:39:14.000 compareTo 09:45:44.000 = -1
        String date = "2015-07-24T09:39:14.000Z";
        //Now we are getting the time only from the above string.
        String time = date.substring(12, 19); 
        System.out.println("Time is: "+time);
        //Since we cannot convert symbols like":" to long we are removing them.
        String timeInLong = time.replaceAll(":", "");
        System.out.println("Time in long format : "+Long.parseLong(timeInLong));

另一种选择是使用 SimpleDateFormat(与 JODA Time 相比可能不是最好的)

public static void main(String[] args) throws ParseException {
        String st1 = "2015-07-24T09:39:14.000Z";
        String st2 = "2015-07-24T09:45:44.000Z";

        String time1 = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));
        String time2 = st2.substring(st2.indexOf("T") + 1, st2.indexOf(".0"));

        Date dateTime1 = new java.text.SimpleDateFormat("HH:mm").parse(time1);
        Date dateTime2 = new java.text.SimpleDateFormat("HH:mm").parse(time2);

        System.out.println(dateTime1.after(dateTime2));

    }

你可以试试下一段代码,我用的是库joda-time

java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2015-07-24T09:45:44.000Z"); long dateLong=new DateTime(ts2).toDate().getTime();

tl;博士

myResultSet.getObject(                         // Use JDBC 4.2 or later to get *java.time* objects rather than mere strings.
    … ,                                        // Specify the column in database of type `TIMESTAMP WITH TIME ZONE`.
    Instant.class                              // Extract from database as a `Instant` object in UTC, via JDBC.
)
.atZone( ZoneId.of( "Africa/Tunis" ) )         // Adjust into a time zone other than UTC. Returns a `ZonedDateTime` object.
.toLocalDate()                                 // Extract the date-only value, without time-of-day and without time zone. Returns a `LocalDate` object.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )   // Determine the first moment of the day (not always 00:00). Returns a `ZonedDateTime` object.

还有……

Duration.between( zdtStartOfDay , zdt )        // Represent the span of time between the first moment of the day and the target moment. Each argument is a `ZonedDateTime` object here.
    .toMillis()                                // Get entire span as a count of milliseconds. Returns a `long` primitive.
  • 不需要字符串。
  • 不需要java.sql.Timestamp

java.time

现代方法使用 java.time classes 取代麻烦的旧遗留 classes,例如 java.sql.Timestamp & Date & Calendar.

使用 java.time 的方向是正确的,但使用了错误的 class: LocalDateTime class 故意缺少任何时区或 offset-from-UTC 的概念,但我们的输入字符串确实如此。输入字符串末尾的 ZZulu 的缩写,表示 UTC。丢弃有价值的信息 (zone/offset 信息) 不是一个好的做法。

Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds(最多九 (9) 位小数)。

Instant instant = Instant.parse( "2015-07-24T09:39:14.000Z" ) ;

智能对象,而不是哑字符串

I have to fetch time stamp from DB and retrieve only time and compare two time.

below are the string values

使用适当的对象与您的数据库交换数据,而不仅仅是字符串。

从JDBC 4.2 开始,您可以通过getObject & setObject 直接交换java.time 对象。

Instant instant = myResultSet( … , Instant.class ) ;

您刚刚从类型类似于 SQL-standard TIMESTAMP WITH TIME ZONE 的数据库列中直接获取了 date-time。

要将数据发送到数据库,请使用带占位符的 PreparedStatement

myPreparedStatement.setObject( … , instant ) ;

根据定义,通过 JDBC 从数据库检索到的 Instant 对象采用 UTC。要获得 time-of-day,您必须指定用户期望的区域(时区)的 wall-clock 时间。

指定 proper time zone name in the format of continent/region, such as America/Montreal, Africa/CasablancaPacific/Auckland。切勿使用 3-4 字母 pseudo-zones,例如 ESTIST,因为它们 不是 真实时区,未标准化,甚至不唯一(!)。

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;

应用该时区以获得 ZonedDateTime 对象。 InstantZonedDateTime代表同一时刻,时间轴上的同一点。这是一个需要理解的关键概念。两个在 phone 上聊天的朋友,一个在加拿大魁北克,一个在法国巴黎,每个人都会在同一时刻同时抬头看墙上的时钟,但会看到他们所在地区的人们使用的时间不同。

ZoneDateTime zdt = instant.atZone( z ) ;

如果您只关心 time-of-day,请提取一个 LocalTime 对象。

LocalTime lt = zdt.toLocalTime(); 

以标准 ISO 8601 格式生成 String

String output = lt.toString();

生成本地化格式的字符串。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = lt.format( f ) ;

但是您似乎想从今天开始就对某事进行计数——您的问题不明确。也许你想要整秒或毫秒的计数,或者我不知道是什么。

我们必须在 desired/expected 时区获取一天的开始时间。不要假设一天从 00:00:00 开始。由于夏令时 (DST) 等异常情况,一天可能会在另一个时间开始,例如 01:00:00。让 java.time 确定一天的开始。

ZonedDateTime zdtStartOfDay = zdt.toLocalDate().atStartOfDay( z ) ;

将经过的时间跨度计算为Duration

Duration d = Duration.between( zdtStartOfDay , zdt ) ;

将整个跨度提取为整数秒数。

long secondsSinceStartOfDay = d.toSeconds() ;

将整个跨度提取为毫秒数。

long millisSinceStartOfDay = d.toMillis() ;

小心数据丢失。 java.time classes 具有纳秒分辨率,因此当您调用 to… 方法时,您将忽略值的更精细部分(如果存在)。


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

从哪里获得java.time classes?

  • Java SE 8, Java SE 9,及以后
    • Built-in。
    • 标准 Java API 的一部分,带有捆绑实施。
    • Java 9 添加了一些小功能和修复。
  • Java SE 6 and Java SE 7
    • java.time 的大部分功能是 back-ported 到 Java ThreeTen-Backport 中的 6 和 7。
  • Android
    • Android java.time classes.
    • 捆绑实施的更高版本
    • 对于较早的 Android (<26),ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See .

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.