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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31715310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:29:20  来源:igfitidea点击:

Convert timestamp string to long in java

javastringnumberformatexception

提问by Thanga

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

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

//below are the string values

//下面是字符串值

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

//retrieving only time 09:39:14

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

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

//string to Long.

//字符串到长。

 Long time = Long.parseLong(s);

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

Error:

错误:

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

采纳答案by TheCodingFrog

Another option is by using SimpleDateFormat (May not be the best compare to JODA Time)

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

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

    }

回答by Bipool

Try this way, Example code:

试试这种方式,示例代码:

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

回答by MadProgrammer

The simplest solution would be to use Java 8's Date/Time API

最简单的解决方案是使用 Java 8 的日期/时间 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));

Which outputs

哪些输出

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

If you're not using Java 8, then use Joda-Timewhich works in similar way

如果您不使用 Java 8,请使用以类似方式工作的Joda-Time

Joda-Time example...

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

}

Which outputs

哪些输出

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

回答by Salim Malik

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

回答by jaimeRambo

you can try with the next code, I use the library joda-time

您可以尝试使用下一个代码,我使用库 joda-time

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

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

回答by Basil Bourque

tl;dr

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.

And…

和…

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.
  • No need for strings.
  • No need for java.sql.Timestamp.
  • 不需要字符串。
  • 不需要java.sql.Timestamp

java.time

时间

The modern approach uses the java.timeclasses that supplant the troublesome old legacy classes such as java.sql.Timestamp& Date& Calendar.

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

The Answer by MadProgrammeris headed in the right direction by using java.timebut uses the wrong class: LocalDateTimeclass purposely lacks any concept of time zone or offset-from-UTC but our input string does. The Zon the end of the input String is short for Zuluand means UTC. Throwing away valuable information (zone/offset info) is not a good practice.

通过MadProgrammer答案是在正确的方向上采用为首java.time,但使用了错误的类:LocalDateTime类特意没有时区的任何概念或偏移从-UTC,但我们的输入字符串一样。的Z所述输入字符串的结尾是短期的Zulu和意味着UTC。丢弃有价值的信息(区域/偏移信息)不是一个好习惯。

The Instantclass represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).

Instant级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。

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

Smart objects, not dumb strings

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

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

below are the string values

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

下面是字符串值

Use appropriate objects to exchange data with your database, not mere strings.

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

As of JDBC 4.2, you can directly exchange java.timeobjects via getObject& setObject.

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

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

You just fetched a date-time directly from a database column of type similar to the SQL-standard TIMESTAMP WITH TIME ZONE.

您只是直接从类似于 SQL-standard 类型的数据库列中获取了日期时间TIMESTAMP WITH TIME ZONE

For sending data to the database, use a PreparedStatementwith placeholders.

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

myPreparedStatement.setObject( … , instant ) ;

The Instantobject retrieved via JDBC from the database is in UTC, by definition. To get the time-of-day, you must specify the wall-clock time of the region expected by the user (the time zone).

根据Instant定义,通过 JDBC 从数据库中检索到的对象采用 UTC 格式。要获取时间,您必须指定用户期望的区域(时区)的挂钟时间。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的伪区域,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

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

Apply that time zone to get a ZonedDateTimeobject. The Instantand the ZonedDateTimerepresent the same moment, the same point on the timeline. This is a crucial concept to understand. Two friends talking on the phone, one in Québec Canada and one in Paris France will each look up to a clock on the wall simultaneously at the same moment yet see a different time in use by the people of their particular region.

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

ZoneDateTime zdt = instant.atZone( z ) ;

If you care only about the time-of-day, extract a LocalTimeobject.

如果您只关心一天中的时间,请提取一个LocalTime对象。

LocalTime lt = zdt.toLocalTime(); 

Generate a Stringin standard ISO 8601format.

生成String标准ISO 8601格式的文件。

String output = lt.toString();

Generate a string in localized format.

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

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

But you seem to want a count of something since the start of the day – your Question is not clear. Perhaps you want a count of whole seconds, or milliseconds, or I don't know what.

但是您似乎想从一天开始就计算一些东西——您的问题不清楚。也许您想要整秒或毫秒的计数,或者我不知道是什么。

We must get the start of the day in the desired/expected time zone. Do not assume the day starts at the time 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. Let java.time determine the start of the day.

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

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

Calculate the elapsed span of time as a Duration.

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

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

Extract the entire span as a number of whole seconds.

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

long secondsSinceStartOfDay = d.toSeconds() ;

Extract the entire span as a number of milliseconds.

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

long millisSinceStartOfDay = d.toMillis() ;

Beware of data loss. The java.timeclasses have resolution of nanoseconds, so you are ignoring the finer parts of the value if present when you call the to…methods.

谨防数据丢失。该java.time类具有纳秒的分辨率,让您忽略的如果存在的话,当你调用价值的细微部分to…的方法。



About java.time

关于java.time

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

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

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

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject 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.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多