本文目錄一覽:
JAVA 中獲取時間怎麼格式化?
時間格式化輸出主要有兩種方式,代碼如下:
//使用Calendar
Calendar now = Calendar.getInstance();
System.out.println(“年:” + now.get(Calendar.YEAR));
System.out.println(“月:” + (now.get(Calendar.MONTH) + 1));
System.out.println(“日:” + now.get(Calendar.DAY_OF_MONTH));
System.out.println(“時:” + now.get(Calendar.HOUR_OF_DAY));
System.out.println(“分:” + now.get(Calendar.MINUTE));
ystem.out.println(“秒:” + now.get(Calendar.SECOND));
//使用Date
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
System.out.println(“當前時間:” + sdf.format(d));
擴展資料
JAVA中獲取當前系統時間。
import java.util.Date;
import java.text.SimpleDateFormat;
public class NowString {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);//設置日期格式
System.out.println(df.format(new Date()));// new Date()為獲取當前系統時間
}
}
參考資料來源:百度百科:Java
java中時間格式化輸出
使用SimpleDateFormat即可,代碼如下
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static String formatDate(Date date)throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
return sdf.format(date);
}
public static Date parse(String strDate) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
return sdf.parse(strDate);
}
}
Java 使用Formatter類格式化輸出日期時間
public class DateFormatDemo {public static void main(String[] args) throws ParseException {// 創建日期對象Date d = new Date();// 給定模式SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);// public final String
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/241661.html