Java日期格式化

java

翻译人员: 铁锚
翻译时间: 2013年11月17日


原文链接:  

Simple example to show how to use Date Formatting in Java



代码示例如下,说明参见注释: 

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

public class TestDate {

/**

* 日期格式化对象,格式: "yyyy-MM-dd"

*/

public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

/**

* 日期时间格式化对象,格式:"yyyy-MM-dd hh:mm:ss",如果需要毫秒值,则可以用三个大写的"SSS" 做格式占位符.

*/

public static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

/**

* 根据地区取得, Locale.CHINA 和 Locale.CHINESE 的格式都是: 2013年11月17日

*/

public static DateFormat localFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA);

public static void main(String[] args) {

// 取得当前时间

Date now = new Date();

// 使用时间戳,距离1970年标准时间的毫秒值来构造对象

Date date2005 = new Date(1134689401756L);

//

String today = formatDate(now);

System.out.println("今天是: " + today);

//

String localDate = localFormat.format(now);

System.out.println("本地日期: " + localDate);

//

String thatTime = formatDateTime(date2005);

System.out.println("当时是: " + thatTime);

}

/**

* 按日期来进行格式化

* @param date

* @return 返回日期字符串

*/

public static String formatDate(Date date){

String result = "";

if(null != date){

return dateFormat.format(date);

}

return result;

}

/**

* 返回时间日期字符串

* @param date

* @return

*/

public static String formatDateTime(Date date){

String result = "";

if(null != date){

return dateTimeFormat.format(date);

}

return result;

}

}


相关阅读:

  1. A simple example to show how to use java properties file
  2. How to Design a Java Framework? – A Simple Example
  3. Simple practice with Scanner in Java
  4. Java vs. Python (1): Simple Code Examples

以上是 Java日期格式化 的全部内容, 来源链接: utcz.com/z/391585.html

回到顶部