现在的位置: 首页 > 综合 > 正文

Java日期的常用方法

2013年10月15日 ⁄ 综合 ⁄ 共 2113字 ⁄ 字号 评论关闭

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

 

public class DateTest {

 static String string = new String();
 static String ymd = new String();
 static String hms = new String();
 static String[] strings = new String[]{};
 static String[] ymdstrings = new String[]{};
 static String[] hmsstrings = new String[]{};
 
 //输出格式为:Thu Sep 10 12:05:05 CST 2009
 public static Date date(){
  Date date = new Date();
  return date;
 }
 
 //输出格式为:2009-9-10 11:50:20
 public static String localDate(){
  Date date = DateTest.date();
  string = date.toLocaleString();
  return string;
 }
 
 //输出格式为:2009年9月10日 12时00分47秒

 //通过切字符串,在拼凑得到结果,实现代码比较多
 public static String localDate2(){
  string = DateTest.localDate();

  //切字符串
  strings = string.split(" ");
  ymdstrings = strings[0].split("-");
  hmsstrings = strings[1].split(":");

  //拼凑字符串
  string = ymdstrings[0]+"年"+ymdstrings[1]+"月"+ymdstrings[2]+"日 "+hmsstrings[0]+"时"+hmsstrings[1]+"分"+hmsstrings[2]+"秒";
  return string;
 }
 

 //输出格式为:2009年09月10日 星期四 02:43:07

 //通过SimpleDateFormat 得到结果,实现代码相对较少

 public static String formatDate(){
  Date date = DateTest.date();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E hh:mm:ss");
  string = sdf.format(date);

  return string;
 }

 

 //找出当前日期是本周的第几天,并找到本周的第一天和最后一天,项目中一周为单位显示查询结果时较为常用
 //今天是本周的第5天,本周的第一天是2009-9-6 14:37:42最后一天是2009-9-12 14:37:42
 public static String dateInWeek(){
  Calendar calendar = Calendar.getInstance();
  Date date = DateTest.date();
  calendar.setTime(date);
  //当日是本周的第几天,从周日算起
  int dayOfWeek = calendar.get(calendar.DAY_OF_WEEK);

//  System.out.println("今天是本周的第"+dayOfWeek+"天");
  //计算本周的第一天,周日--weekFirstDay
  calendar.add(calendar.DATE, -dayOfWeek+1);
  Date weekFirstDay = calendar.getTime();

  calendar.setTime(date);
  //计算本周的最后一天,周六--weekLastDay
  calendar.add(calendar.DATE, +(7-dayOfWeek));
  Date weekLastDay = calendar.getTime();

  string = "今天是本周的第"+dayOfWeek+"天,本周的第一天是"+weekFirstDay.toLocaleString()+",最后一天是"+weekLastDay.toLocaleString();
  return string;
 }

 

 //测试
 public static void main(String[] args){
  System.out.println(DateTest.date());
  System.out.println(DateTest.localDate());
  System.out.println(DateTest.localDate2());
  System.out.println(DateTest.formatDate());
  System.out.println(DateTest.dateInWeek());
 }
}

抱歉!评论已关闭.