熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

java獲取當前日期時間代碼

2022-06-13   來源: JSP教程 

  獲取當前時間和某個時間進行比較此時主要拿long型的時間值

  方法如下

  要使用 javautilDate 獲取當前時間的代碼如下

代碼如下  

  Date date = new Date();

  dategetTime() ;

  還有一種方式使用 SystemcurrentTimeMillis() ;

  都是得到一個當前的時間的long型的時間的毫秒值這個值實際上是當前時間值與年一月一號零時零分零秒相差的毫秒數

  一獲取當前時間 格式為: yyyymmdd hhmmss

  DateFormatgetDateTimeInstance( LocaleCHINESE)format(new javautilDate());

  二獲取當前時間 格式為: yyyy年mm月dd日 上午/下午hh時mm分ss秒

代碼如下  

  DateFormatgetDateTimeInstance(DateFormatLONG DateFormatLONG LocaleCHINESE)format(new javautilDate());

  三獲取當前時間(精確到毫秒) 格式為: yyyymmdd hh:mm:ssnnn

代碼如下  

  new javasqlTimestamp(SystemcurrentTimeMillis())toString();

  一 獲取當前系統時間和日期並格式化輸出:

代碼如下  

  import javautilDate;
import javatextSimpleDateFormat;

  public class NowString {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");//設置日期格式
Systemoutprintln(dfformat(new Date()));// new Date()為獲取當前系統時間
}
}

  二 在數據庫裡的日期只以年日的方式輸出可以用下面兩種方法

  用convert()轉化函數

代碼如下  

  String sqlst = "select convert(varchar()bookDate) as convertBookDate from roomBook where bookDate between and ";

  Systemoutprintln(rsgetString("convertBookDate"));

  利用SimpleDateFormat類

  先要輸入兩個java包

  import javautilDate;

  import javatextSimpleDateFormat;

  然後

  定義日期格式SimpleDateFormat sdf = new SimpleDateFormat(yyMMdd);

  sql語句為String sqlStr = "select bookDate from roomBook where bookDate between and ";

  輸出

  Systemoutprintln(dfformat(rsgetDate("bookDate")));

  java中獲取當前日期和時間的方法

代碼如下  

  import javautilDate;
import javautilCalendar;

  import javatextSimpleDateFormat;

  public class TestDate{
public static void main(String[] args){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式

  
String hehe = dateFormatformat( now );
Systemoutprintln(hehe);

  Calendar c = CalendargetInstance();//可以對每個時間域單獨修改

  

  
int year = cget(CalendarYEAR);
int month = cget(CalendarMONTH);
int date = cget(CalendarDATE);
int hour = cget(CalendarHOUR_OF_DAY);
int minute = cget(CalendarMINUTE);
int second = cget(CalendarSECOND);
Systemoutprintln(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second);
}
}

  有時候要把String類型的時間轉換為Date類型通過以下的方式就可以將你剛得到的時間字符串轉換為Date類型了

  SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");

  javautilDate time=null;
try {
time= sdfparse(sdfformat(new Date()));

  } catch (ParseException e) {

  eprintStackTrace();
}

  一個不錯日期時間類

代碼如下  

  package comwondersgroupcccti;

  
import javasqlTimestamp;
import javautilCalendar;
import javautilDate;

  
public class TestGetSystemTime {

  
static Date nowTime = null;

  
/**
* @param args
*/
public static void main(String[] args) {

  
// 以下為 Clendar 測試代碼
int yyyy mm dd;
Calendar c = CalendargetInstance();
yyyy = cget(CalendarYEAR);
mm = cget(CalendarMONTH) + ;
dd = cget(CalendarDAY_OF_MONTH);
Systemoutprintln("year = "+yyyy);
Systemoutprintln("month = "+mm);
Systemoutprintln("day = "+dd);

// SystemcurrentTimeMillis() 獲取系統時間的代碼
Timestamp ts = new Timestamp(SystemcurrentTimeMillis());
String dateStr = tstoString();
Systemoutprintln("SystemcurrentTimeMillis() = "+dateStr);

// date 為獲得系統時間的另外一種方法
Date date = new Date();
String dateStr = new Timestamp(dategetTime())toString();
Systemoutprintln(dateStr);

// 得到JAVA運行環境的一些基本屬性
SystemgetProperties()list(Systemout);
}

  
}

  一個完整的獲取日期實例

  
格式化日期 String>Date 或者 Data>String
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = sdfparse("");//String>Date
String sdate = sdfformat(date );// Data>String ===============================================================
package comhefengtest;
import javatextDateFormat;
import javatextParsePosition;
import javatextSimpleDateFormat;
import javautilCalendar;
import javautilDate;
import javautilGregorianCalendar;
public class TimeTest {
//用來全局控制 上一周本周下一周的周數變化
private int weeks = ;
private int MaxDate;//一月最大天數
private int MaxYear;//一年最大天數
/**
* @param args
*/
public static void main(String[] args) {
TimeTest tt = new TimeTest();
Systemoutprintln("得到個月後的日期:"+tt getAfterMonth();
Systemoutprintln("獲取當天日期:"+ttgetNowTime("yyyyMMdd"));
Systemoutprintln("獲取本周一日期:"+ttgetMondayOFWeek());
Systemoutprintln("獲取本周日的日期~:"+ttgetCurrentWeekday());
Systemoutprintln("獲取上周一日期:"+ttgetPreviousWeekday());
Systemoutprintln("獲取上周日日期:"+ttgetPreviousWeekSunday());
Systemoutprintln("獲取下周一日期:"+ttgetNextMonday());
Systemoutprintln("獲取下周日日期:"+ttgetNextSunday());
Systemoutprintln("獲得相應周的周六:"+ttgetNowTime("yyyyMMdd"));
Systemoutprintln("獲取本月第一天日期:"+ttgetFirstDayOfMonth());
Systemoutprintln("獲取本月最後一天日期:"+ttgetDefaultDay());
Systemoutprintln("獲取上月第一天日期:"+ttgetPreviousMonthFirst());
Systemoutprintln("獲取上月最後一天的日期:"+ttgetPreviousMonthEnd());
Systemoutprintln("獲取下月第一天日期:"+ttgetNextMonthFirst());
Systemoutprintln("獲取下月最後一天日期:"+ttgetNextMonthEnd());
Systemoutprintln("獲取本年的第一天日期:"+ttgetCurrentYearFirst());
Systemoutprintln("獲取本年最後一天日期:"+ttgetCurrentYearEnd());
Systemoutprintln("獲取去年的第一天日期:"+ttgetPreviousYearFirst());
Systemoutprintln("獲取去年的最後一天日期:"+ttgetPreviousYearEnd());
Systemoutprintln("獲取明年第一天日期:"+ttgetNextYearFirst());
Systemoutprintln("獲取明年最後一天日期:"+ttgetNextYearEnd());
Systemoutprintln("獲取本季度第一天到最後一天:"+ttgetThisSeasonTime());
Systemoutprintln("獲取兩個日期之間間隔天數~
:"+TimeTestgetTwoDay(""""));
}
/**
* 得到指定月後(前)的日期 參數傳負數即可
*/
public static String getAfterMonth(int month) {
Calendar c = CalendargetInstance();//獲得一個日歷的實例
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = null;
try{
date = sdfparse("");//初始日期
}catch(Exception e){
}
csetTime(date);//設置日歷時間
cadd(CalendarMONTHmonth);//在日歷的月份上增加個月
String strDate = sdfformat(cgetTime()));//的到你想要得個月後的日期
return strDate;
}

  /**
* 得到二個日期間的間隔天數
*/
public static String getTwoDay(String sj String sj) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMdd");
long day = ;
try {
javautilDate date = myFormatterparse(sj);
javautilDate mydate = myFormatterparse(sj);
day = (dategetTime() mydategetTime()) / ( * * * );
} catch (Exception e) {
return "";
}
return day + "";
}
/**
* 根據一個日期返回是星期幾的字符串
*/
public static String getWeek(String sdate) {
// 再轉換為時間
Date date = TimeTeststrToDate(sdate);
Calendar c = CalendargetInstance();
csetTime(date);
// int hour=cget(CalendarDAY_OF_WEEK);
// hour 中存的就是星期幾了其范圍 ~
// =星期日 =星期六其他類推
return new SimpleDateFormat("EEEE")format(cgetTime());
}
/**
* 將短時間格式字符串轉換為時間 yyyyMMdd
*/
public static Date strToDate(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
ParsePosition pos = new ParsePosition();
Date strtodate = formatterparse(strDate pos);
return strtodate;
}
/**
* 兩個時間之間的天數
*
* @param date
* @param date
* @return
*/
public static long getDays(String date String date) {
if (date == null || dateequals(""))
return ;
if (date == null || dateequals(""))
return ;
// 轉換為標准時間
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMdd");
javautilDate date = null;
javautilDate mydate = null;
try {
date = myFormatterparse(date);
mydate = myFormatterparse(date);
} catch (Exception e) {
}
long day = (dategetTime() mydategetTime()) / ( * * * );
return day;
}
// 計算當月最後一天返回字符串
public String getDefaultDay(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateset(CalendarDATE);//設為當前月的
lastDateadd(CalendarMONTH);//加一個月變為下月的
lastDateadd(CalendarDATE);//減去一天變為當月最後一天
str=sdfformat(lastDategetTime());
return str;
}
// 上月第一天
public String getPreviousMonthFirst(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateset(CalendarDATE);//設為當前月的
lastDateadd(CalendarMONTH);//減一個月變為下月的
//lastDateadd(CalendarDATE);//減去一天變為當月最後一天
str=sdfformat(lastDategetTime());
return str;
}
//獲取當月第一天
public String getFirstDayOfMonth(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateset(CalendarDATE);//設為當前月的
str=sdfformat(lastDategetTime());
return str;
}
// 獲得本周星期日的日期
public String getCurrentWeekday() {
weeks = ;
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus+);
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
//獲取當天時間
public String getNowTime(String dateformat){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);//可
以方便
地修改日期格式
String hehe = dateFormatformat(now);
return hehe;
}
// 獲得當前日期與本周日相差的天數
private int getMondayPlus() {
Calendar cd = CalendargetInstance();
// 獲得今天是一周的第幾天星期日是第一天星期二是第二天
int dayOfWeek = cdget(CalendarDAY_OF_WEEK); //因為按中國禮拜一
作為第一
天所以這裡減
if (dayOfWeek == ) {
return ;
} else {
return dayOfWeek;
}
}
//獲得本周一的日期
public String getMondayOFWeek(){
weeks = ;
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus);
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
//獲得相應周的周六的日期
public String getSaturday() {
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus + * weeks + );
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
// 獲得上周星期日的日期
public String getPreviousWeekSunday() {
weeks=;
weeks;
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus+weeks);
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
// 獲得上周星期一的日期
public String getPreviousWeekday() {
weeks;
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus + * weeks);
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
// 獲得下周星期一的日期
public String getNextMonday() {
weeks++;
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus + );
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
// 獲得下周星期日的日期
public String getNextSunday() {
int mondayPlus = thisgetMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATE mondayPlus + +);
Date monday = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preMonday = dfformat(monday);
return preMonday;
}
private int getMonthPlus(){
Calendar cd = CalendargetInstance();
int monthOfNumber = cdget(CalendarDAY_OF_MONTH);
cdset(CalendarDATE );//把日期設置為當月第一天
cdroll(CalendarDATE );//日期回滾一天也就是最後一天
MaxDate=cdget(CalendarDATE);
if(monthOfNumber == ){
return MaxDate;
}else{
return monthOfNumber;
}
}
//獲得上月最後一天的日期
public String getPreviousMonthEnd(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateadd(CalendarMONTH);//減一個月
lastDateset(CalendarDATE );//把日期設置為當月第一天
lastDateroll(CalendarDATE );//日期回滾一天也就是本月最後一天
str=sdfformat(lastDategetTime());
return str;
}
//獲得下個月第一天的日期
public String getNextMonthFirst(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateadd(CalendarMONTH);//減一個月
lastDateset(CalendarDATE );//把日期設置為當月第一天
str=sdfformat(lastDategetTime());
return str;
}
//獲得下個月最後一天的日期
public String getNextMonthEnd(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateadd(CalendarMONTH);//加一個月
lastDateset(CalendarDATE );//把日期設置為當月第一天
lastDateroll(CalendarDATE );//日期回滾一天也就是本月最後一天
str=sdfformat(lastDategetTime());
return str;
}
//獲得明年最後一天的日期
public String getNextYearEnd(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateadd(CalendarYEAR);//加一個年
lastDateset(CalendarDAY_OF_YEAR );
lastDateroll(CalendarDAY_OF_YEAR );
str=sdfformat(lastDategetTime());
return str;
}
//獲得明年第一天的日期
public String getNextYearFirst(){
String str = "";
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Calendar lastDate = CalendargetInstance();
lastDateadd(CalendarYEAR);//加一個年
lastDateset(CalendarDAY_OF_YEAR );
str=sdfformat(lastDategetTime());
return str;
}
//獲得本年有多少天
private int getMaxYear(){
Calendar cd = CalendargetInstance();
cdset(CalendarDAY_OF_YEAR);//把日期設為當年第一天
cdroll(CalendarDAY_OF_YEAR);//把日期回滾一天
int MaxYear = cdget(CalendarDAY_OF_YEAR);
return MaxYear;
}
private int getYearPlus(){
Calendar cd = CalendargetInstance();
int yearOfNumber = cdget(CalendarDAY_OF_YEAR);//獲得當天是一年中的第幾天
cdset(CalendarDAY_OF_YEAR);//把日期設為當年第一天
cdroll(CalendarDAY_OF_YEAR);//把日期回滾一天
int MaxYear = cdget(CalendarDAY_OF_YEAR);
if(yearOfNumber == ){
return MaxYear;
}else{
return yearOfNumber;
}
}
//獲得本年第一天的日期
public String getCurrentYearFirst(){
int yearPlus = thisgetYearPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATEyearPlus);
Date yearDay = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preYearDay = dfformat(yearDay);
return preYearDay;
}
//獲得本年最後一天的日期 *
public String getCurrentYearEnd(){
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方
便地修
改日期格式
String years = dateFormatformat(date);
return years+"";
}
//獲得上年第一天的日期 *
public String getPreviousYearFirst(){
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方
便地修
改日期格式
String years = dateFormatformat(date); int years_value = IntegerparseInt
(years);
years_value;
return years_value+"";
}
//獲得上年最後一天的日期
public String getPreviousYearEnd(){
weeks;
int yearPlus = thisgetYearPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDateadd(GregorianCalendarDATEyearPlus+MaxYear*weeks+(MaxYear));
Date yearDay = currentDategetTime();
DateFormat df = DateFormatgetDateInstance();
String preYearDay = dfformat(yearDay);
getThisSeasonTime();
return preYearDay;
}
//獲得本季度
public String getThisSeasonTime(int month){
int array[][] = {{}{}{}{}};
int season = ;
if(month>=&&month<=){
season = ;
}
if(month>=&&month<=){
season = ;
}
if(month>=&&month<=){
season = ;
}
if(month>=&&month<=){
season = ;
}
int start_month = array[season][];
int end_month = array[season][];
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方
便地修
改日期格式
String years = dateFormatformat(date);
int years_value = IntegerparseInt(years);
int start_days =;//years+""+StringvalueOf(start_month)+"
";//getLastDayOfMonth(years_valuestart_month);
int end_days = getLastDayOfMonth(years_valueend_month);
String seasonDate =
years_value+""+start_month+""+start_days+";"+years_value+""+end_month+""+end_days;
return seasonDate;
}
/**
* 獲取某年某月的最後一天
* @param year 年
* @param month 月
* @return 最後一天
*/
private int getLastDayOfMonth(int year int month) {
if (month == || month == || month == || month == || month ==
|| month == || month == ) {
return ;
}
if (month == || month == || month == || month == ) {
return ;
}
if (month == ) {
if (isLeapYear(year)) {
return ;
} else {
return ;
}
}
return ;
}
/**
* 是否閏年
* @param year 年
* @return
*/
public boolean isLeapYear(int year) {
return (year % == && year % != ) || (year % == );
}


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19983.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.