1. 程式人生 > >java常見日期格式轉換以及日期的獲取

java常見日期格式轉換以及日期的獲取

try get sdf for exc ins 第一天 trace util

package com.test.TestBoot.SingleModel;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {

/**
* Date 轉 String
*/
Date date = new Date();
String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);


System.out.println(dateStr);


/**
*String 轉 Date
*/
String ss = "2016-10-24 21:59:06";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date d = sdf.parse(ss);
System.out.println(d);
} catch (ParseException e) {

e.printStackTrace();
}

/**
* 本月第一天
*/
Calendar monthca = Calendar.getInstance();
monthca.add(Calendar.MONTH, 0);
monthca.set(Calendar.DAY_OF_MONTH,1);
String monthfirstDay = sdf.format(monthca.getTime()); //本月第一天
System.out.println(monthfirstDay);

/**
* 本月最後一天
*/
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
String monthlastday = sdf.format(calendar.getTime()); //本月最後一天
System.out.println(monthlastday);

/**
* 昨天
*/
Calendar startca = Calendar.getInstance(); // 得到一個Calendar的實例
startca.setTime(new Date()); // 設置時間為當前時間
startca.add(Calendar.DATE, -1); // 日期減1
Date sDate = startca.getTime(); //前一天的時間
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
String starttime = sd.format(sDate); //前一天的時間(昨天)
System.out.println(starttime);

/**
* 上個月第一天
*/
Calendar lastmonthfirst = Calendar.getInstance();
lastmonthfirst.add(Calendar.MONTH, -1);
lastmonthfirst.set(Calendar.DAY_OF_MONTH, 1);
String lastmonthfirstday = sd.format(lastmonthfirst.getTime()); //上個月第一天
System.out.println(lastmonthfirstday);

/**
* 上個月最後一天
*/
Calendar lastmonthlast = Calendar.getInstance();
lastmonthlast.set(Calendar.DAY_OF_MONTH, 1);
lastmonthlast.add(Calendar.DATE, -1);
String lastmonthlastday = sd.format(lastmonthlast.getTime()); //上個月最後一天
System.out.println(lastmonthlastday);


}

}

java常見日期格式轉換以及日期的獲取