Java Date应用实例集1


//取得指定月份的第一天与取得指定月份的最后一天
http://iamin.blogdriver.com/iamin/847990.html
/** *//**
* 取得指定月份的第一天
*
* @param strdate String
* @return String
*/

public String getMonthBegin(String strdate)
...{
java.util.Date date = parseFormatDate(strdate);
return formatDateByFormat(date,"yyyy-MM") + "-01";
}

/** *//**
* 取得指定月份的最后一天
*
* @param strdate String
* @return String
*/
public String getMonthEnd(String strdate)
...{
java.util.Date date = parseFormatDate(getMonthBegin(strdate));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH,1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return formatDate(calendar.getTime());
}

/** *//**
* 常用的格式化日期
*
* @param date Date
* @return String
*/
public String formatDate(java.util.Date date)
...{
return formatDateByFormat(date,"yyyy-MM-dd");
}

/** *//**
* 以指定的格式来格式化日期
*
* @param date Date
* @param format String
* @return String
*/
public String formatDateByFormat(java.util.Date date,String format)
...{
String result = "";
if(date != null)
...{
try
...{
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.format(date);
}
catch(Exception ex)
...{
LOGGER.info("date:" + date);
ex.printStackTrace();
}
}
return result; package com.app.util;

/** *//**
* 日期操作
*
* @author xxx
* @version 2.0 jdk1.4.0 tomcat5.1.0 * Updated Date:2005/03/10
*/
public class DateUtil ...{
/** *//**
* 格式化日期
*
* @param dateStr
* 字符型日期
* @param format
* 格式
* @return 返回日期
*/
public static java.util.Date parseDate(String dateStr, String format) ...{
java.util.Date date = null;
try ...{
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
String dt=Normal.parse(dateStr).replaceAll(
"-", "/");
if((!dt.equals(""))&&(dt.length()<format.length()))...{
dt+=format.substring(dt.length()).replaceAll("[YyMmDdHhSs]","0");
}
date = (java.util.Date) df.parse(dt);
} catch (Exception e) ...{
}
return date;
}

public static java.util.Date parseDate(String dateStr) ...{
return parseDate(dateStr, "yyyy/MM/dd");
}

public static java.util.Date parseDate(java.sql.Date date) ...{
return date;
}

public static java.sql.Date parseSqlDate(java.util.Date date) ...{
if (date != null)
return new java.sql.Date(date.getTime());
else
return null;
}

public static java.sql.Date parseSqlDate(String dateStr, String format) ...{
java.util.Date date = parseDate(dateStr, format);
return parseSqlDate(date);
}

public static java.sql.Date parseSqlDate(String dateStr) ...{
return parseSqlDate(dateStr, "yyyy/MM/dd");
}


public static java.sql.Timestamp parseTimestamp(String dateStr,
String format) ...{
java.util.Date date = parseDate(dateStr, format);
if (date != null) ...{
long t = date.getTime();
return new java.sql.Timestamp(t);
} else
return null;
}

public static java.sql.Timestamp parseTimestamp(String dateStr) ...{
return parseTimestamp(dateStr, "yyyy/MM/dd HH:mm:ss");
}

/** *//**
* 格式化输出日期
*
* @param date
* 日期
* @param format
* 格式
* @return 返回字符型日期
*/
public static String format(java.util.Date date, String format) ...{
String result = "";
try ...{
if (date != null) ...{
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
result = df.format(date);
}
} catch (Exception e) ...{
}
return result;
}

public static String format(java.util.Date date) ...{
return format(date, "yyyy/MM/dd");
}

/** *//**
* 返回年份
*
* @param date
* 日期
* @return 返回年份
*/
public static int getYear(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.YEAR);
}

/** *//**
* 返回月份
*
* @param date
* 日期
* @return 返回月份
*/
public static int getMonth(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MONTH) + 1;
}

/** *//**
* 返回日份
*
* @param date
* 日期
* @return 返回日份
*/
public static int getDay(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.DAY_OF_MONTH);
}

/** *//**
* 返回小时
*
* @param date
* 日期
* @return 返回小时
*/
public static int getHour(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.HOUR_OF_DAY);
}

/** *//**
* 返回分钟
*
* @param date
* 日期
* @return 返回分钟
*/
public static int getMinute(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MINUTE);
}

/** *//**
* 返回秒钟
*
* @param date
* 日期
* @return 返回秒钟
*/
public static int getSecond(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.SECOND);
}

/** *//**
* 返回毫秒
*
* @param date
* 日期
* @return 返回毫秒
*/
public static long getMillis(java.util.Date date) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.getTimeInMillis();
}

/** *//**
* 返回字符型日期
*
* @param date
* 日期
* @return 返回字符型日期
*/
public static String getDate(java.util.Date date) ...{
return format(date, "yyyy/MM/dd");
}

/** *//**
* 返回字符型时间
*
* @param date
* 日期
* @return 返回字符型时间
*/
public static String getTime(java.util.Date date) ...{
return format(date, "HH:mm:ss");
}

/** *//**
* 返回字符型日期时间
*
* @param date
* 日期
* @return 返回字符型日期时间
*/
public static String getDateTime(java.util.Date date) ...{
return format(date, "yyyy/MM/dd HH:mm:ss");
}

/** *//**
* 日期相加
*
* @param date
* 日期
* @param day
* 天数
* @return 返回相加后的日期
*/
public static java.util.Date addDate(java.util.Date date, int day) ...{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTimeInMillis(getMillis(date) + ((long) day) * 24 * 3600 * 1000);
return c.getTime();
}

/** *//**
* 日期相减
*
* @param date
* 日期
* @param date1
* 日期
* @return 返回相减后的日期
*/
public static int diffDate(java.util.Date date, java.util.Date date1) ...{
return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
}
}class CalendaUseing ...{
//日历类的应用
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int date = now.get(Calendar.DAY_OF_MONTH);
int month = now.get(Calendar.MONTH) + 1;
int hour = now.get(Calendar.HOUR);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
}
package com.infoearth;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
public class ManageWeek ...{
//判断两个日期是否在同一周
boolean isSameWeekDates(Date date1, Date date2) ...{
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR); import java.text.DateFormat;
import java.util.*;

public class JspCalendar ...{
Calendar calendar = null;

public JspCalendar() ...{
calendar = Calendar.getInstance();
Date trialTime = new Date();
calendar.setTime(trialTime);
}

public int getYear() ...{
return calendar.get(Calendar.YEAR);
}

public String getMonth() ...{
int m = getMonthInt();
String[] months = new String [] ...{ "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" };
if (m > 12)
return "Unknown to Man";

return months[m - 1];

}

public String getDay() ...{
int x = getDayOfWeek();
String[] days = new String[] ...{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};

if (x > 7)
return "Unknown to Man";

return days[x - 1];

}

public int getMonthInt() ...{
return 1 + calendar.get(Calendar.MONTH);
}

public String getDate() ...{
return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear();

}

public String getTime() ...{
return getHour() + ":" + getMinute() + ":" + getSecond();
}

public int getDayOfMonth() ...{
return calendar.get(Calendar.DAY_OF_MONTH);
}

public int getDayOfYear() ...{
return calendar.get(Calendar.DAY_OF_YEAR);
}

public int getWeekOfYear() ...{
return calendar.get(Calendar.WEEK_OF_YEAR);
}

public int getWeekOfMonth() ...{
return calendar.get(Calendar.WEEK_OF_MONTH);
}

public int getDayOfWeek() ...{
return calendar.get(Calendar.DAY_OF_WEEK);
}

public int getHour() ...{
return calendar.get(Calendar.HOUR_OF_DAY);
}

public int getMinute() ...{
return calendar.get(Calendar.MINUTE);
}


public int getSecond() ...{
return calendar.get(Calendar.SECOND);
}

public static void main(String args[]) ...{
JspCalendar db = new JspCalendar();
p("date: " + db.getDayOfMonth());
p("year: " + db.getYear());
p("month: " + db.getMonth());
p("time: " + db.getTime());
p("date: " + db.getDate());
p("Day: " + db.getDay());
p("DayOfYear: " + db.getDayOfYear());
p("WeekOfYear: " + db.getWeekOfYear());
p("era: " + db.getEra());
p("ampm: " + db.getAMPM());
p("DST: " + db.getDSTOffset());
p("ZONE Offset: " + db.getZoneOffset());
p("TIMEZONE: " + db.getUSTimeZone());
}

private static void p(String x) ...{
System.out.println(x);
}


public int getEra() ...{
return calendar.get(Calendar.ERA);
}

public String getUSTimeZone() ...{
String[] zones = new String[] ...{"Hawaii", "Alaskan", "Pacific",
"Mountain", "Central", "Eastern"};

return zones[10 + getZoneOffset()];
}

public int getZoneOffset() ...{
return calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000);
}


public int getDSTOffset() ...{
return calendar.get(Calendar.DST_OFFSET)/(60*60*1000);
}


public int getAMPM() ...{
return calendar.get(Calendar.AM_PM);
}
}
public static Calendar getDateFromIDCard(String IDCardNum)...{
int year, month, day, idLength = IDCardNum.length();
Calendar cal = Calendar.getInstance();

if(idLength == 18)...{
year = Integer.parseInt(IDCardNum.substring(6,10));
month = Integer.parseInt(IDCardNum.substring(10,12));
day = Integer.parseInt(IDCardNum.substring(12,14));
}
else if(idLength == 15)...{
year = Integer.parseInt(IDCardNum.substring(6,8)) + 1900;
month = Integer.parseInt(IDCardNum.substring(8,10));
day = Integer.parseInt(IDCardNum.substring(10,12));
}
else ...{
return null;
}
cal.set(year, month, day);
return cal;
}

public static int getWorkDay(Date d1, Date d2)...{
int[] freeDays = ...{0, 6};//default: Sunday and Saturday are the free days.
return getWorkDay(d1, d2, freeDays);
}

public static int getFreeDay(Date date, int dNum)...{
int[] freeDays = ...{0, 6};//default: Sunday and Saturday are the free days.
return getFreeDay(date, dNum, freeDays);
}

public static int getWorkDay(Date d1, Date d2, int[] freeDays)...{
int dNum = 0;
dNum = (int) ((d2.getTime() - d1.getTime()) / 1000 / 60 / 60 /24) + 1;

return dNum - getFreeDay(d1, dNum, freeDays);
}

public static int getFreeDay(Date date, int dNum, int[] freeDays)...{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int start = cal.get(Calendar.DAY_OF_WEEK) - 1;
int freeNum = 0;
for(int i = 0; i < dNum; i++)...{
for(int j = 0; j < freeDays.length; j++)...{
if((start + i) % 7 == freeDays[j])...{
freeNum++;
}
}
}
return freeNum;
}

/** *//**
* 日期相加
*
* @param date
* 日期
* @param day
* 天数
* @return 返回相加后的日期
*/
public static Date changeDay(Date date, int offset)...{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_YEAR,(calendar.get(Calendar.DAY_OF_YEAR) + offset));
return calendar.getTime();
}

public static Calendar changeDay(Calendar calendar, int offset)...{
calendar.set(Calendar.DAY_OF_YEAR,(calendar.get(Calendar.DAY_OF_YEAR) + offset));
return calendar;
}

//判断两个日期是否在同一周
static boolean isSameWeekDates(Date date1, Date date2) ...{
long diff = getMonday(date1).getTime() - getMonday(date2).getTime();
if(Math.abs(diff) < 1000 * 60 * 60 * 24)...{
return true;
}
else...{
return false;
}
}

//获得周一的日期
public static Date getMonday(Date date)...{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
return c.getTime();
}

/** *//**
* 日期相减
*
* @param date
* 日期
* @param date1
* 日期
* @return 返回相减后的日期
*/
public static int getDiffDate(java.util.Date date, java.util.Date date1) ...{
return (int) ((date.getTime() - date1.getTime()) / (24 * 3600 * 1000));
}

public static int getDiffDate(Calendar date, Calendar date1) ...{
return getDiffDate(date.getTime(), date1.getTime());
}

/** *//**
* 格式化日期
*
* @param dateStr
* 字符型日期
* @param formatStr
* 格式
* @return 返回日期
*/
public static java.util.Date parseDate(String dateStr, String formatStr) ...{
SimpleDateFormat format = new SimpleDateFormat(formatStr);
try ...{
return format.parse(dateStr);
} catch (ParseException e) ...{
e.printStackTrace();
return null;
}
}

public static boolean isLeapYear(int year)...{
Calendar calendar = Calendar.getInstance();
calendar.set(year, 2, 1);
calendar.add(Calendar.DATE, -1);
if (calendar.get(Calendar.DAY_OF_MONTH) == 29) ...{
System.out.println(year + " year is a leap year.");
return true;
} else ...{
System.out.println(year + " year is not a leap year.");
return false;
}
}

if (0 == subYear) ...{
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) ...{
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) ...{
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}


//产生周序列
public static String getSeqWeek()...{
Calendar c = Calendar.getInstance(Locale.CHINA);
String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
if(week.length()==1)week = "0" + week;
String year = Integer.toString(c.get(Calendar.YEAR));
return year+week;

}

//获得周一的日期
public static String getMonday(Date date)...{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}


//获得周五的日期
public static String getFriday(Date date)...{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK,Calendar.FRIDAY);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
public static void main(String[] args)...{
}
}
/**//*上面的都是jdk中的类,给一个Jakarta Commons Lang的

在Java中处理日期和时间是一件相当棘手的事。如果要使用java.text.SimpleDateFormat、 java.util.Calendar、java.util.Date等类,需要一定时间来适应,还需要对每一个涉及到的类和接口非常了解,才能顺利地处理日期和时间。
  Lang组件彻底地简化了日期的处理,并可对其进行格式化。您可以轻松地格式化日期以进行显示、比较日期、舍入或截断日期,甚至能获取特定范围内的所有日期。 */

//清单4. 处理日期和时间
public static void main(String[] args) throws InterruptedException, ParseException ...{
//date1 created
Date date1= new Date();
//Print the date and time at this instant
System.out.println("The time right now is >>"+date1);

//Thread sleep for 1000 ms
Thread.currentThread().sleep(DateUtils.MILLIS_IN_SECOND);

//date2 created.
Date date2= new Date();

//Check if date1 and date2 have the same day
System.out.println("Is Same Day >> "
+ DateUtils.isSameDay(date1, date2));

//Check if date1 and date2 have the same instance
System.out.println("Is Same Instant >> "
+DateUtils.isSameInstant(date1, date2));

//Round the hour
System.out.println("Date after rounding >>"
+DateUtils.round(date1, Calendar.HOUR));

//Truncate the hour
System.out.println("Date after truncation >>"
+DateUtils.truncate(date1, Calendar.HOUR));

//Three dates in three different formats
String [] dates=...{"2005.03.24 11:03:26", "2005-03-24 11:03", "2005/03/24"};

//Iterate over dates and parse strings to java.util.Date objects
for(int i=0; i < dates.length; i++)...{
Date parsedDate= DateUtils.parseDate(dates[i],
new String []...{"yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm"});

System.out.println("Parsed Date is >>"+parsedDate);
}

//Display date in HH:mm:ss format
System.out.println("Now >>"
+DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis()));
} 
 
/**//*清单4演示了org.apache.commons.lang.DateUtils和 org.apache.commons.lang.DateFormatStringUtils类的部分功能。还有其他许多方法可以进行同样的操作,但输入格式不同。故而,如果万一您必须分析和格式化一个日期值,只需要借助提供的方法之一,利用一行代码就可以实现了。
  执行清单4中代码后的输入如清单5所示。*/

//清单5. 输出
The time right now is >>Sat Apr 09 14:40:41 GMT+05:30 2005
Is Same Day >> true
Is Same Instant >> false
Date after rounding >>Sat Apr 09 15:00:00 GMT+05:30 2005
Date after truncation >>Sat Apr 09 14:00:00 GMT+05:30 2005
Parsed Date is >>Thu Mar 24 11:03:26 GMT+05:30 2005
Parsed Date is >>Thu Mar 24 11:03:00 GMT+05:30 2005
Parsed Date is >>Thu Mar 24 00:00:00 GMT+05:30 2005
Now >>14:40:43
  /**//*在清单4中,我们创建了两个日期,这两个日期仅有一秒的差别。然后使用isSameInstant()和isSameDay()方法检查这两个日期是否相同。接下来将日期进行舍入和截断,然后使用在数组中指定的各种格式对特殊日期用例进行解析。
  将您的应用程序集成到第三方应用程序时,经常不能完全确定输入的格式。我曾经做过一个对旧版应用程序的集成,对于每个问题,该应用程序似乎总是有三个答案。所以,如果必须对此类应用程序提供的日期进行解析,您需要提供三个和四个不同的日期格式。清单4中使用parseDate()方法就是为了完成这项任务。这样,即使输入有变化,仍然能更对日期进行解析。还要注意,数组内模式的顺序与输入的顺序并不相同,但该方法仍然找到了适当的模式,并据此进行解析。
  最后,我们按照ISO_TIME_NO_T_FORMAT格式(HH:mm:ss)对日期进行格式化并打印输入。*/
阅读更多
文章标签: Java C C++ C# Apache
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭