Extract time from date String

JavaStringDateTime

Java Problem Overview


How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?

Java Solutions


Solution 1 - Java

Use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat (click the blue code link for the Javadoc).

Here's a kickoff example:

String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00

Solution 2 - Java

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Solution 3 - Java

Solution 4 - Java

The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:

	String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
			.format(DateTimeFormatter.ofPattern("H:mm"));

The result is the desired, 9:00.

Solution 5 - Java

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Solution 6 - Java

If you have date in integers, you could use like here:

Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);

Solution 7 - Java

let datestring = "2017-02-14 02:16:28"

let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full

formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJJuniorView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaAdamView Answer on Stackoverflow
Solution 3 - JavaPetrView Answer on Stackoverflow
Solution 4 - JavaOle V.V.View Answer on Stackoverflow
Solution 5 - JavaMikeTheReaderView Answer on Stackoverflow
Solution 6 - JavaBohdan KolesnykView Answer on Stackoverflow
Solution 7 - JavaBHAVIKView Answer on Stackoverflow