`
RednaxelaFX
  • 浏览: 3013612 次
  • 性别: Icon_minigender_1
  • 来自: 海外
社区版块
存档分类
最新评论

一些获取当前日期的方法

阅读更多
好几天没写东西了……新年什么的事情特别多 OTL
这几天一直在应付考试。总算都考完了。另外也读了好些以前没接触过的方面的资料,像是Programming Ruby之类。收获不少,不过没时间在这边记录。话说Programming Ruby和Ruby Cookbook的中文版分别是99和98元,现在的技术书真是太贵了 =_=|||

记点小东西。获取带格式的当前日期/时间的方法。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:
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
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#:
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:
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)
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
<?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
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()来获取当前时间。
分享到:
评论
3 楼 lwwin 2008-01-05  
当时希望能够用BAT做一个和获得时间相关的东东+……+
结果是很囧的

PS:有这种EXE就好了,不过偶机器没.NETFRAMEWORK……
2 楼 RednaxelaFX 2008-01-04  
__DATE__ __TIME__ %date% 这些都无法定制,在这里可以说是毫无用处。不在这讨论范围内。
所以还是喜欢.NET Framework版的那个……
1 楼 lwwin 2008-01-04  
%date%

相关推荐

Global site tag (gtag.js) - Google Analytics