如何从java中的字符串时间戳中提取日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21796497/
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
How to extract date and time from a String Timestamp in java
提问by Rakesh
I am getting date and time as a String
TIMESTAMP
from MySQL from a server in such a format:
我String
TIMESTAMP
从服务器以这种格式从 MySQL获取日期和时间:
2014-02-15 05:18:08
What I want is to extract the Date in DD-MM-YYYY
format and the time in HH:MM:SS AM/PM
format. Also the timezone of this timestamp is different and I want it in Indian Timezone(IST).
我想要的是提取DD-MM-YYYY
格式的日期和格式的时间HH:MM:SS AM/PM
。此时间戳的时区也不同,我希望它在印度时区(IST)中。
Remember the timestamp
is of String
datatype.
记住timestamp
是String
数据类型。
采纳答案by Yatendra Goel
Use java.text.SimpleDateFormat
and java.util.TimeZone
使用java.text.SimpleDateFormat
和java.util.TimeZone
Which timezone the date string is in? Replace the below UTC
timezone with that timezone
日期字符串在哪个时区?用该UTC
时区替换以下时区
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-02-15 05:18:08");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
sdf2.setTimeZone(TimeZone.getTimeZone("IST"));
String dateStr = sdf2.format(date); // Output: 15-02-2014 10:48:08 AM
Note:In which format the hour is in (24 hour/ 12 hour) in your input string? The above example assumes that it is in 24 hour format because there in no AM/PM info in the input string.
注意:您的输入字符串中的小时采用哪种格式(24 小时/12 小时)?上面的示例假定它采用 24 小时格式,因为输入字符串中没有 AM/PM 信息。
If the input string is also in 12 hour format then your input string should mention AM/PM info also such as 2014-02-15 05:18:08 PM
. In that case, modify the sdf
to new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")
如果输入字符串也是 12 小时格式,那么您的输入字符串也应提及 AM/PM 信息,例如2014-02-15 05:18:08 PM
. 在这种情况下,修改sdf
为new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")
======================== Edited:=====================
======================== 编辑:====================
To answer your next question in comment "How to extract date and time separately"...
要在评论“如何分别提取日期和时间”中回答您的下一个问题...
SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MM-yyyy");
sdfDate.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a");
sdfTime.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
String dateStr = sdfDate.format(date);
String timeStr = sdfTime.format(date);
回答by Rebirth
you can use DATE_FORMAT(date,format).
您可以使用 DATE_FORMAT(date,format)。
in your case it'd be something like this:
在你的情况下,它会是这样的:
SELECT DATE_FORMAT(timestamp, '%e-%c-%Y') FROM table WHERE...
-edit: the code above will return your timestamp as : "DD-MM-YYYY".
- 编辑:上面的代码将您的时间戳返回为:“DD-MM-YYYY”。
timestamp being your mySQL field (in other words: column).
时间戳是您的 mySQL 字段(换句话说:列)。
for other format options I'd recommend you to have a quick look at: DATE_FORMAT options
对于其他格式选项,我建议您快速查看: DATE_FORMAT options
回答by user3259926
Use a SimpleDateFormat like:-
使用 SimpleDateFormat 像:-
String s = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(yourTimestamp);
For more info SimpleDateFormat.
有关更多信息 SimpleDateFormat。
回答by Basil Bourque
The accepted answer by Yatendra Goelis correct.
Yatendra Goel接受的答案是正确的。
Joda-Time
乔达时间
For fun, here's the same kind of code using the Joda-Time2.3 library.
为了好玩,这里是使用Joda-Time2.3 库的相同类型的代码。
Note that Joda-Timeis now in maintenance mode. The team advises migration to java.time. See my other Answerfor java.timecode.
请注意,Joda-Time现在处于维护模式。该团队建议迁移到 java.time。见我的其他回答了java.time代码。
FYI… India is five and a halfhours ahead of UTC/GMT. Hence the thirty minute difference in the outputs below.
仅供参考......印度比UTC/ GMT早五个半小时。因此,下面的输出存在三十分钟的差异。
String input = "2014-02-15 05:18:08";
input = input.replace( " ", "T" ); // Replace space in middle with a "T" to get ISO 8601 format.
// Parse input as DateTime in UTC/GMT.
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
// Adjust to India time.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTime = dateTimeUtc.withZone( timeZone );
// Using "en" for English here because (a) it is irrelevant in our case, and (b) I don't know any Indian language codes.
java.util.Locale localeIndiaEnglish = new Locale( "en", "IN" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "SS" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
String output = formatter.print( dateTime );
DateTimeFormatter formatterDateOnly = DateTimeFormat.forPattern( "dd-MM-yyyy" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
DateTimeFormatter formatterTimeOnly = DateTimeFormat.forPattern( "hh:mm:ss a" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
String dateOnly = formatterDateOnly.print( dateTime );
String timeOnly = formatterTimeOnly.print( dateTime );
Dump to console…
转储到控制台...
System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTime: " + dateTime );
System.out.println( "output: " + output );
System.out.println( "dateOnly: " + dateOnly );
System.out.println( "timeOnly: " + timeOnly );
When run…
运行时…
input: 2014-02-15T05:18:08
dateTimeUtc: 2014-02-15T05:18:08.000Z
dateTime: 2014-02-15T10:48:08.000+05:30
output: 15/2/14 10:48 AM
dateOnly: 15-02-2014
timeOnly: 10:48:08 AM
回答by Basil Bourque
tl;dr
tl;博士
ZonedDateTime zdt = LocalDateTime.parse( "2014-02-15 05:18:08".replace( " " , "T" ) ).atOffset( ZoneOffset.UTC ).atZoneSameInstant( ZoneId.of( "Asia/Kolkata" ) ) ;
LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();
Use objects, not strings
使用对象,而不是字符串
You should be retrieving date-time values from your database as date-time objects rather than Strings.
您应该从数据库中检索日期时间值作为日期时间对象而不是字符串。
As of JDBC 4.2 and later, we can exchange java.timeobjects with the database.
从 JDBC 4.2 及更高版本开始,我们可以与数据库交换java.time对象。
Instant instant = Instant.now() ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , instant ) ;
Retrieval.
恢复。
Instant instant = myResultSet.getObject( … , Instant.class ) ;
java.time
时间
The java.timeclasses in Java 8 and later supplant the troublesome old legacy date-time classes as well as the 3rd-party Joda-Time library.
Java 8 和更高版本中的java.time类取代了麻烦的旧日期时间类以及第 3 方 Joda-Time 库。
- The
java.sql.Timestamp
class is replaced byInstant
. - The
java.sql.Date
class is replaced byLocalDate
. - The
java.sql.Time
class is replaced byLocalTime
. -
- 该
java.sql.Timestamp
班所取代Instant
。 - 该
java.sql.Date
班所取代LocalDate
。 - 该
java.sql.Time
班所取代LocalTime
。 ——
Parsing String
解析字符串
If you are stuck with such a String, parse it using a java.time classes. The other Answers are using the troublesome old date-time classes bundled with the earliest versions of Java. Those are now legacy, and should be avoided.
如果您遇到这样的字符串,请使用 java.time 类解析它。其他答案正在使用与最早版本的 Java 捆绑在一起的麻烦的旧日期时间类。这些现在都是遗留问题,应该避免。
Your input string is almost in standard ISO 8601format. Merely replace the SPACE in the middle with a T
.
您的输入字符串几乎采用标准ISO 8601格式。只需将中间的 SPACE 替换为T
.
String input = "2014-02-15 05:18:08".replace( " " , "T" ) ;
LocalDateTime
LocalDateTime
Parse as a LocalDateTime
as the string lacks any info about offset-from-UTCor time zone.
解析为 a ,LocalDateTime
因为该字符串缺少有关从 UTC或时区偏移的任何信息。
LocalDateTime ldt = LocalDateTime.parse( input ) ;
OffsetDateTime
OffsetDateTime
I will assume the value in your input String was intended to be a moment in UTCtime zone. So adjust into UTC.
我将假设您的输入字符串中的值是UTC时区中的某个时刻。所以调整为UTC。
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime
ZonedDateTime
You asked for this to be adjusted into the India timezone, which is five and a half hours ahead of UTC.
您要求将其调整为印度时区,比 UTC 早五个半小时。
The atZoneSameInstant
means the resulting ZonedDateTime
represents the very same simultaneous moment as the OffsetDateTime
. The two are different only in that they view that same moment through two different lenses of wall-clock time.
该atZoneSameInstant
机构由此而来ZonedDateTime
表示非常相同的同时时刻的OffsetDateTime
。两者的不同仅在于他们通过挂钟时间的两个不同镜头观看同一时刻。
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
LocalDate
& LocalTime
LocalDate
& LocalTime
If you want to work with the date portion and time-of-day portion separately, extract each as a Local…
.
如果要分别处理日期部分和时间部分,请将每个部分提取为Local…
.
LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();
Generating String representation
生成字符串表示
The toString
method on the classes all generate a String representation using standard ISO 8601formats. To use other formats, use the DateTimeFormatter
class. Search Stack Overflow for many examples and discussions.
在toString
对类方法全部使用标准生成的字符串表示ISO 8601格式。要使用其他格式,请使用DateTimeFormatter
类。在 Stack Overflow 上搜索许多示例和讨论。
The easiest way is let the class automatically localize for you. Specify a Locale
for the desired human language and the desired cultural norms to decide issues such as capitalization, abbreviation, and such.
最简单的方法是让类自动为您本地化。Locale
为所需的人类语言和所需的文化规范指定 a以决定大小写、缩写等问题。
Locale locale = new Locale( "en" , "IN" ); // English language, India cultural norms.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT ).withLocale( locale );
String output = zdt.format( f );
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 类?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
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 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。