Rakesh Rakesh - 3 months ago 17
Java Question

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.

Answer

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