JAVA 擷取系統目前時間執行個體代碼_java

來源:互聯網
上載者:User

本文章向大家講解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()為擷取當前系統時間}}

 二. 在資料庫裡的日期只以年-月-日的方式輸出,可以用下面兩種方法:

1、用convert()轉化函數:

String sqlst = "select convert(varchar(10),bookDate,126) as convertBookDate from roomBook where bookDate between '2007-4-10' and '2007-4-25'";System.out.println(rs.getString("convertBookDate"));

2、利用SimpleDateFormat類:

先要輸入兩個java包:

import java.util.Date;
import java.text.SimpleDateFormat;

然後定義日期格式:

SimpleDateFormat sdf = new SimpleDateFormat(yy-MM-dd);

sql語句為:

String sqlStr = "select bookDate from roomBook where bookDate between '2007-4-10' and '2007-4-25'";

輸出:

System.out.println(df.format(rs.getDate("bookDate")));

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

import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; 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 = dateFormat.format( now ); System.out.println(hehe); Calendar c = Calendar.getInstance();//可以對每個時間域單獨修改int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int date = c.get(Calendar.DATE); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second); } }

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

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");java.util.Date time=null;try {  time= sdf.parse(sdf.format(new Date()));} catch (ParseException e) {  e.printStackTrace();}

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.