获得系统当前时间的字符串格式
生活随笔
收集整理的這篇文章主要介紹了
获得系统当前时间的字符串格式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
通過java.util.Calendar類以及java.util.Date類來獲得系統(tǒng)的當前時間
1. 使用Calendar類時,要通過該類對象的get()方法獲得時間中的年月日小時分鐘秒組成一個字符串
2. 使用Date類時,可以通過java.text.SimpleDateFormat類將一個Date對象格式化為指定格式的日期時間字符串
JavaBean類
public class StringUtil3 {private String timeStr1; //日期字符串private String timeStr2;public String getTimeStr1() {Calendar c = Calendar.getInstance(); //創(chuàng)建表示當前時間的Calendar對象int year = c.get(c.YEAR); //獲得當前時間的年int month =c.get(c.MONTH)+1; //獲得當前時間的月int date = c.get(c.DAY_OF_MONTH); //獲得當前時間的日int hour = c.get(c.HOUR_OF_DAY); //獲得當前時間的小時int minute = c.get(c.MINUTE); //獲得當前時間的分鐘int second = c.get(c.SECOND); //獲得當前時間的秒timeStr1 = year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;return timeStr1;}public void setTimeStr1(String timeStr1) {this.timeStr1 = timeStr1;}public String getTimeStr2() {Date date = new Date(); //創(chuàng)建表示當前時間的Date對象//創(chuàng)建格式化日期時間對象SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");timeStr2 = format.format(date);//格式化當前時間的Date對象return timeStr2;}public void setTimeStr2(String timeStr2) {this.timeStr2 = timeStr2;}public static void main(String [] args){Date d = new Date();StringUtil s = new StringUtil();} }index.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%request.setCharacterEncoding("UTF-8");%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <title>轉換為Calendar對象</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css">table{border: 1px solid;border-color: green;color: green;font-size: 13px;font-family: 華文細黑;}</style></head><body><!-- 使用useBean動作標簽導入JavaBean對象 --><jsp:useBean id="strBean" class="com.cn.zj.bean.StringUtil3"></jsp:useBean><table><tr><td align="right">使用Calendar對象獲得的當前時間:</td><td><!-- 從StringUtil對象中獲得timeStr1的屬性值 --> <jsp:getProperty property="timeStr1" name="strBean"/></td></tr><tr ><td align="right" >使用Date對象獲得的當前時間:</td><td > <!-- 從StringUtil對象中獲得timeStr2的屬性值 --> <jsp:getProperty property="timeStr2" name="strBean"/></td> </tr></table> </body> </html>總結
以上是生活随笔為你收集整理的获得系统当前时间的字符串格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将Calendar对象转换为日期时间字符
- 下一篇: 计算两个日期相差的天数