4

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.

Rakesh
  • 1,133
  • 4
  • 13
  • 28
  • Use a `SimpleDateFormat` instance for parsing. – qqilihq Feb 15 '14 at 10:58
  • By the way, avoid 3-letter time zone codes. They are neither standardized nor unique. Your use of `IST` can mean "Irish Standard Time" as well as "India Standard Time". Instead, use a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) such as "Asia/Kolkata". – Basil Bourque Feb 16 '14 at 07:48

5 Answers5

5

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);
Amit
  • 33,847
  • 91
  • 226
  • 299
  • Thanks Yatendra for helping.It worked flawlessly. I am new to java actually. Can you please tell me how can I extract Date and Time individually as a String ? Actually I am programming for android and I want to display Date and Time in its own textviews. – Rakesh Feb 15 '14 at 11:24
  • Ok figured it out myself by just altering the format string. Thanks man it helped me a lot. Thanks ! – Rakesh Feb 15 '14 at 11:31
1

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
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • @RafiAbro Glad to help. But be aware that the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). See [my other Answer](https://stackoverflow.com/a/39046312/642706) for *java.time*. – Basil Bourque Apr 15 '18 at 19:54
  • oh, what will happen to those applications in which I have used joda-Time.. – mrabro Apr 25 '18 at 15:24
  • @RafiAbro Joda-Time continues to be actively maintained with bug fixes and updates to it bundled [*tzdata*](https://en.wikipedia.org/wiki/Tz_database). But no further development of features. When convenient, you should rework your apps to use *java.time* classes. But not urgent. The transition is fairly easy as the two projects share the same concepts and the same leader, Stephen Colebourne. – Basil Bourque Apr 25 '18 at 16:50
0

Use a SimpleDateFormat like:-

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

For more info SimpleDateFormat.

0

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1

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

Rebirth
  • 1,011
  • 8
  • 14