简体   繁体   中英

How to extract date and time from a String Timestamp in java

I am getting date and time as a String TIMESTAMP from MySQL from a server in such a format:

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

Remember the timestamp is of String datatype.

Use java.text.SimpleDateFormat and java.util.TimeZone

Which timezone the date string is in? Replace the below UTC timezone with that timezone

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.

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

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

The accepted answer by Yatendra Goel is correct.

Joda-Time

For fun, here's the same kind of code using the Joda-Time 2.3 library.

Note that Joda-Time is now in maintenance mode . The team advises migration to java.time. See my other Answer for java.time code.

FYI… India is five and a half hours ahead of UTC /GMT. Hence the thirty minute difference in the outputs below.

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

you can use 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".

timestamp being your mySQL field (in other words: column).

for other format options I'd recommend you to have a quick look at: DATE_FORMAT options

Use a SimpleDateFormat like:-

String s = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(yourTimestamp);

For more info SimpleDateFormat .

tl;dr

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.time objects with the database.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.
myPreparedStatement.setObject( … , instant ) ;

Retrieval.

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

java.time

The java.time classes in Java 8 and later supplant the troublesome old legacy date-time classes as well as the 3rd-party Joda-Time library.

  • The java.sql.Timestamp class is replaced by Instant .
  • The java.sql.Date class is replaced by LocalDate .
  • The java.sql.Time class is replaced by 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.

Your input string is almost in standard ISO 8601 format. Merely replace the SPACE in the middle with a T .

String input = "2014-02-15 05:18:08".replace( " " , "T" ) ;

LocalDateTime

Parse as a LocalDateTime as the string lacks any info about offset-from-UTC or time zone.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

OffsetDateTime

I will assume the value in your input String was intended to be a moment in UTC time zone. So adjust into UTC.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;

ZonedDateTime

You asked for this to be adjusted into the India time zone, which is five and a half hours ahead of 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 .

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );

LocalDate & LocalTime

If you want to work with the date portion and time-of-day portion separately, extract each as a 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 8601 formats. To use other formats, use the DateTimeFormatter class. Search Stack Overflow for many examples and discussions.

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

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

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

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

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

Where to obtain the java.time classes?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM