Extract time from date String

2019-01-03 09:51发布

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

8条回答
Animai°情兽
2楼-- · 2019-01-03 09:54
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

查看更多
爷的心禁止访问
3楼-- · 2019-01-03 09:56
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)
查看更多
小情绪 Triste *
4楼-- · 2019-01-03 09:58

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
查看更多
劫难
5楼-- · 2019-01-03 10:03

A very simple way is to use Formatter (see date time conversions) or more directly String.format as in

String.format("%tR", new Date())
查看更多
狗以群分
6楼-- · 2019-01-03 10:04

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);
查看更多
淡お忘
7楼-- · 2019-01-03 10:08

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.

查看更多
登录 后发表回答