使用自定义格式格式化时间的 Java 程序
首先,使用 SimpleDateFormat 类设置时间
Format dateFormat = new SimpleDateFormat("h:m:s");现在,对于自定义格式,让我们单独获取小时、分钟和秒
小时
// hour
dateFormat = new SimpleDateFormat("h");
String strHour = dateFormat.format(new Date());
System.out.println("Hour: "+strHour);分钟
// minute
dateFormat = new SimpleDateFormat("m");
String strMinute = dateFormat.format(new Date());
System.out.println("Minute: "+strMinute);秒
// second
dateFormat = new SimpleDateFormat("s");
String strSecond = dateFormat.format(new Date());
System.out.println("Second: "+strSecond);以下是一个示例 −
示例
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] argv) throws Exception {
Format dateFormat = new SimpleDateFormat("h:m:s");
String str = dateFormat.format(new Date());
System.out.println("Time: "+str);
// hour
dateFormat = new SimpleDateFormat("h");
String strHour = dateFormat.format(new Date());
System.out.println("Hour: "+strHour);
// minute
dateFormat = new SimpleDateFormat("m");
String strMinute = dateFormat.format(new Date());
System.out.println("Minute: "+strMinute);
// second
dateFormat = new SimpleDateFormat("s");
String strSecond = dateFormat.format(new Date());
System.out.println("Second: "+strSecond);
}
}输出
Time: 10:58:52 Hour: 10 Minute: 58 Second: 52
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP