Java日期的常用方法

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());
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值