本文目錄一覽:
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 formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);\x0d\x0aDate currentTime = new Date();// 得到當前系統時間\x0d\x0aString str_date = formatter.format(currentTime); // 將日期時間格式化\x0d\x0aSystem.out.print(str_date );\x0d\x0a這樣肯定沒問題啊
Java格式化字元串日期
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateStyle {
public static void main(String[] args) {
SimpleDateFormat dateformat1 = new SimpleDateFormat(
“yyyyMMddHHmmss”);
Date date=new Date();
date.setYear(2014-1900);
date.setMonth(3-1);
date.setDate(29);
date.setHours(19);
date.setMinutes(13);
date.setSeconds(0);
String a1 = dateformat1.format(date);
System.out.println(“時間2:” + a1);
}
}
效果:
時間2:20140329191300
希望能幫到你。
或者因為那個方法都過時了,你可以用Calendar的方法,代碼如下:
package test;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateStyle {
public static void main(String[] args) {
SimpleDateFormat dateformat1 = new SimpleDateFormat(“yyyyMMddHHmmss”);
Calendar c = dateformat1.getCalendar();
c.set(2013, 14, 29, 19, 13, 0);
Date d = c.getTime();
System.out.println(d);
String a1 = dateformat1.format(d);
System.out.println(“時間2:” + a1);
}
}
效果:
Sat Mar 29 19:13:00 CST 2014
時間2:20140329191300
望採納。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/238604.html