程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java中一些獲取當前日期的方法

Java中一些獲取當前日期的方法

編輯:關於JAVA

記點小東西。獲取帶格式的當前日期/時間的方法。C#的ToString()果然還是我覺得最有愛的format方 式。不過腳本語言一般也都會提供非常方便的方法,像PHP、Perl和Ruby等等都有相當不錯的方法; JavaScript雖然沒提供format方法,但自己寫一個不廢什麼事。

我們都知道C/C++裡提供了__DATE__和__TIME__宏,不過這兩個宏記錄的是編譯時的日期和時間,而且 無法自定義格式,跟這裡討論的可以說是完全沒關系……

============================================================

DOS Batch File(on Windows NT):

主要依靠命令行的date /T與time /T命令來分別獲取當前系統日期和時間。

例子:

2008-01-05 星期六

11:20

http://www.robvanderwoude.com/datetiment.html

============================================================

Java:

Java代碼

import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;

public class Greet {
	public static void main(String[] args) {
		DateFormat df
			= DateFormat.getDateTimeInstance(
				DateFormat.FULL, DateFormat.SHORT, Locale.CHINA);
		String message = df.format(new Date());
		System.out.println(message);
	}
}

// 2008年1月4日 星期五 下午07:54

Java裡相關的幾個類算是java.util.Date,java.util.Time,java.util.Calendar, java.text.DateFormat,java.text.SimpleDateFormat等。

這裡的例子裡我沒有使用自定義格式,直接用了標准格式中的DateFormat.FULL所指定的格式。

如果使用SimpleDateFormat則可以指定自定義格式的參數:

引用

Letter  Date or Time Component  Presentation  Examples 
G  Era designator  Text  AD 
y  Year  Year  1996; 96 
M  Month in year  Month  July; Jul; 07 
w  Week in year  Number  27 
W  Week in month  Number  2 
D  Day in year  Number  189 
d  Day in month  Number  10 
F  Day of week in month  Number  2 
E  Day in week  Text  Tuesday; Tue 
a  Am/pm marker  Text  PM 
H  Hour in day (0-23)  Number  0 
k  Hour in day (1-24)  Number  24 
K  Hour in am/pm (0-11)  Number  0 
h  Hour in am/pm (1-12)  Number  12 
m  Minute in hour  Number  30 
s  Second in minute  Number  55 
S  Millisecond  Number  978 
z  Time zone  General time zone  Pacific Standard Time; PST; GMT-08:00 
Z  Time zone  RFC 822 time zone  -0800

============================================================

Scala:

Java代碼

import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._

object ChinaDate {
  def main(args: Array[String]) {
    val now = new Date
    val df = getDateInstance(LONG, Locale.CHINA)
    println(df format now)
  }
}

Java平台上的一種函數式腳本語言。它可以依靠Java的標准庫來完成操作,所以跟Java放在一起來記 錄。

============================================================

Velocity:

http://www.java2s.com/Code/Java/Velocity/HowtouseDateinVelocity.htm

============================================================

C#:

C#代碼

using System;

sealed class Greet {
	static void Main(string[] args) {
		string nowString
			= DateTime.Now.ToString("yyyy年MM月dd日 dddd tt hh時mm分");
		Console.WriteLine(nowString);
	}
}

// 2008年01月04日 星期五 下午 08時11分

格式參數可以參考MSDN: .NET Framework Developer's Guide - Standard Date and Time Format Strings

引用MSDN上的簡明表格如下:(http://msdn2.microsoft.com/en- us/library/system.globalization.datetimeformatinfo.aspx

標准格式:

引用

Format pattern
Associated Property/Description
d
ShortDatePattern
D
LongDatePattern
f
Full date and time (long date and short time)
F
FullDateTimePattern (long date and long time)
g
General (short date and short time)
G
General (short date and long time)
m, M
MonthDayPattern
o, O
Round-trip date/time pattern; with this format pattern, the formatting or parsing operation always uses the invariant culture
r, R
RFC1123Pattern; with this format pattern, the formatting or parsing operation always uses the invariant culture
s
SortableDateTimePattern (based on ISO 8601) using local time; with this format pattern, the formatting or parsing operation always uses the invariant culture
t
ShortTimePattern
T
LongTimePattern
u
UniversalSortableDateTimePattern using the format for universal time display; with this format pattern, the formatting or parsing operation always uses the invariant culture
U
Full date and time (long date and long time) using universal time
y, Y
YearMonthPattern

自定義格式:

引用

Format pattern
Description
d, %d
The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.
dd
The day of the month. Single-digit days have a leading zero.
ddd
The abbreviated name of the day of the week, as defined in AbbreviatedDayNames.
dddd
The full name of the day of the week, as defined in DayNames.
f, %f
The fraction of a second in single-digit precision. The remaining digits are truncated. The application specifies "%f" if the format pattern is not combined with other format patterns.
ff
The fraction of a second in double-digit precision. The remaining digits are truncated.
fff
The fraction of a second in three-digit precision. The remaining digits are truncated.
ffff
The fraction of a second in four-digit precision. The remaining digits are truncated.
fffff
The fraction of a second in five-digit precision. The remaining digits are truncated.
ffffff
The fraction of a second in six-digit precision. The remaining digits are truncated.
fffffff
The fraction of a second in seven-digit precision. The remaining digits are truncated.
F, %F
Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. The application specifies "%F" if the format pattern is not combined with other format patterns.
FF
Displays the two most significant digits of the seconds fraction. However, trailing zeros, or two zero digits, are not displayed.
FFF
Displays the three most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed.
FFFF
Displays the four most significant digits of the seconds fraction. However, trailing zeros, or four zero digits, are not displayed.
FFFFF
Displays the five most significant digits of the seconds fraction. However, trailing zeros, or five zero digits, are not displayed.
FFFFFF
Displays the six most significant digits of the seconds fraction. However, trailing zeros, or six zero digits, are not displayed.
FFFFFFF
Displays the seven most significant digits of the seconds fraction. However, trailing zeros, or seven zero digits, are not displayed.
gg
The period or era. This pattern is ignored if the date to be formatted does not have an associated period or era string.
h, %h
The hour in a 12-hour clock. Single-digit hours do not have a leading zero. The application specifies "%h" if the format pattern is not combined with other format patterns.
hh
The hour in a 12-hour clock. Single-digit hours have a leading zero.
H, %H
The hour in a 24-hour clock. Single-digit hours do not have a leading zero. The application specifies "%H" if the format pattern is not combined with other format patterns.
HH
The hour in a 24-hour clock. Single-digit hours have a leading zero.
K
Different values of the Kind property, that is, Local, Utc, or Unspecified.
m, %m
The minute. Single-digit minutes do not have a leading zero. The application specifies "%m" if the format pattern is not combined with other format patterns.
mm
The minute. Single-digit minutes have a leading zero.
M, %M
The numeric month. Single-digit months do not have a leading zero. The application specifies "%M" if the format pattern is not combined with other format patterns.
MM
The numeric month. Single-digit months have a leading zero.
MMM
The abbreviated name of the month, as defined in AbbreviatedMonthNames.
MMMM
The full name of the month, as defined in MonthNames.
s, %s
The second. Single-digit seconds do not have a leading zero. The application specifies "%s" if the format pattern is not combined with other format patterns.
ss
The second. Single-digit seconds have a leading zero.
t, %t
The first character in the AM/PM designator defined in AMDesignator or PMDesignator, if any. The application specifies "%t" if the format pattern is not combined with other format patterns.
tt
The AM/PM designator defined in AMDesignator or PMDesignator, if any. Your application should use this format pattern for languages for which it is necessary to maintain the distinction between AM and PM. An example is Japanese, for which the AM and PM designators differ in the second character instead of the first character.
y, %y
The year without the century. If the year without the century is less than 10, the year is displayed with no leading zero. The application specifies "%y" if the format pattern is not combined with other format patterns.
yy
The year without the century. If the year without the century is less than 10, the year is displayed with a leading zero.
yyy
The year in three digits. If the year is less than 100, the year is displayed with a leading zero.
yyyy
The year in four or five digits (depending on the calendar used), including the century. Pads with leading zeros to get four digits. Thai Buddhist and Korean calendars have five- digit years. Users selecting the "yyyy" pattern see all five digits without leading zeros for calendars that have five digits. Exception: the Japanese and Taiwan calendars always behave as if "yy" is selected.
yyyyy
The year in five digits. Pads with leading zeros to get five digits. Exception: the Japanese and Taiwan calendars always behave as if "yy" is selected.
yyyyyy
The year in six digits. Pads with leading zeros to get six digits. Exception: the Japanese and Taiwan calendars always behave as if "yy" is selected. The pattern can be continued with a longer string of "y"s padding with more leading zeros.
z, %z
The time zone offset ("+" or "-" followed by the hour only). Single-digit hours do not have a leading zero. For example, Pacific Standard Time is "-8". The application specifies "%z" if the format pattern is not combined with other format patterns.
zz
The time zone offset ("+" or "-" followed by the hour only). Single-digit hours have a leading zero. For example, Pacific Standard Time is "-08".
zzz
The full time zone offset ("+" or "-" followed by the hour and minutes). Single-digit hours and minutes have leading zeros. For example, Pacific Standard Time is "-08:00".
:
The default time separator defined in TimeSeparator.
/
The default date separator defined in DateSeparator.
% c
Where c is a format pattern if used alone. To use format pattern "d", "f", "F", "h", "m", "s", "t", "y", "z", "H", or "M" by itself, the application specifies "%d", "%f", "%F", "%h", "%m", "%s", "%t", "%y", "%z", "%H", or "%M".
The "%" character can be omitted if the format pattern is combined with literal characters or other format patterns.
\c
Where c is any character. Displays the character literally. To display the backslash character, the application should use "\\".

C#另外有DateTime.UtcNow,用於獲取當前的UTC時間。

雖然是用C#來說,其它在.NET Framework上運行的程序語言當然也能用同樣的類庫,例如說C++/CLI、 VB.NET、JScript.NET等,不重復記錄了。

JavaScript:

Js代碼

var now = new Date(); var nowString = date.toLocaleString()+' 星期'+'日一二三四五六'.charAt(date.getDay()); print(nowString); // 2008年1月4日 20:19:48 星期五

JavaScript沒有內建的對日期的format方法。通常的做法是自己寫一個方法接到 Date.prototype.format上,通過使用getYear()、getMonth()、getDay()等方法與正則表達式配合來實現 根據format string指定輸出的日期格式。

上面的方法是豆腐寫的,多謝哦。能用這種簡短的方法來寫還是多得JavaScript采用UNICODE為內置字 符編碼。像Ruby就沒辦法直接用String#[]和fixnum#chr來處理非ASCII字符。

D: (引用自 http://www.digitalmars.com/d/phobos/std_date.html)

Java代碼

import std.date;

void main(char[][] args) {

    // Grab the date and time relative to UTC
    d_time lNow = std.date.getUTCtime();
    
    // Convert this into the local date and time for display.
    char[] lNowString = std.date.toString(lNow);
    
    printf("%.*s", lNowString);
}

// Fri Jan 04 23:16:58 GMT+0800 2008

D(Phobos)裡的d_time基本上就是用UTC時間的。轉換成別的形式時才帶上時區等的計算。

不過D的標准庫目前對英語以外的語言還是不夠友善,可惜。

另外Phobos裡這toString()的輸出形式固定是"Www Mmm dd hh:mm:ss GMT+-TZ yyyy"。另外的 toDateString()是"Www Mmm dd yyyy",而toTimeString()是"hh:mm:ss GMT+-TZ"。

PHP:

Java代碼

<?php echo $showtime=date("Y年n月j日 H時i分A");?> <!-- 2008年1月4日 11時56分PM -->

格式參數:

引用

相關時間參數:

a - "am" 或是 "pm"
A - "AM" 或是 "PM"
d - 幾日,二位數字,若不足二位則前面補零; 如: "01" 至 "31"
D - 星期幾,三個英文字母; 如: "Fri"
F - 月份,英文全名; 如: "January"
h - 12 小時制的小時; 如: "01" 至 "12"
H - 24 小時制的小時; 如: "00" 至 "23"
g - 12 小時制的小時,不足二位不補零; 如: "1" 至 12"
G - 24 小時制的小時,不足二位不補零; 如: "0" 至 "23"
i - 分鐘; 如: "00" 至 "59"
j - 幾日,二位數字,若不足二位不補零; 如: "1" 至 "31"
l - 星期幾,英文全名; 如: "Friday"
m - 月份,二位數字,若不足二位則在前面補零; 如: "01" 至 "12"
n - 月份,二位數字,若不足二位則不補零; 如: "1" 至 "12"
M - 月份,三個英文字母; 如: "Jan"
s - 秒; 如: "00" 至 "59"
S - 字尾加英文序數,二個英文字母; 如: "th","nd"
t - 指定月份的天數; 如: "28" 至 "31"
U - 總秒數
w - 數字型的星期幾,如: "0" (星期日) 至 "6" (星期六)
Y - 年,四位數字; 如: "1999"
y - 年,二位數字; 如: "99"
z - 一年中的第幾天; 如: "0" 至 "365"

我不熟悉PHP,無法肯定這東西有沒有寫錯……

Ruby:

Ruby代碼

dayOfWeek = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ] t = Time.now nowString = t.strftime("%Y年%m月%d日 ") << dayOfWeek[t.strftime("%w").to_i] << t.strftime(" %H:%M %p") puts nowString # 2008年01月05日 星期六 00:25 AM

引用

%a - The abbreviated weekday name (``Sun'')
%A - The full weekday name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The full month name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM'' or ``PM'')
%S - Second of the minute (00..60)
%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character

Ruby這邊基本上就是通過Date和Time來解決這問題。有Date::today和Time::now,另外就是 Date::strftime和Time::strftime。不過Ruby在對中文的支持上也還是不夠好啊(還是說我沒弄清楚該怎 麼用?),要是能指定Locale就好了。

Time實例裡有完整的時間信息,從年份到秒都有記錄。而Date只記錄到天,並且有更加嚴格的檢查( 以及對Gregorian歷法的不同支持等)。

Perl:

Perl的話,裝上Date::Format會方便很多。以往的做法是通過localtime()獲取毫秒的時間,然後通過 Date::Format提供的time2str()函數來轉換成自定義的格式。不過從Perl6開始提供了date()和utcdate() 來獲取當前時間。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved