Rakesh Rakesh - 1 year ago 150
Java Question

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

I am getting date and time as a

from MySQL from a server in such a format:

2014-02-15 05:18:08

What I want is to extract the Date in
format and the time in
format. Also the timezone of this timestamp is different and I want it in Indian Timezone(IST).

Remember the
is of

Answer Source

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");
Date date = sdf.parse("2014-02-15 05:18:08");

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
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");

SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a");

String dateStr = sdfDate.format(date);
String timeStr = sdfTime.format(date);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download