Q:对于一个格式化的日期字符串,读出这个日期,并要检测一下这个日期是否是有效的。
A:先parse(),再format(),比较一下两次的字符串是否相等。
import java.util.*;
import java.text.*;
public class 格式化日期
{
public static void main(String[] args)
{
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str="2017-11-25 06:40:99";
try
{
//将格式化字符串转换为日期
Date date=format.parse(str);
System.out.println(date);
//再次把时间转换为字符串,看转换后的字符串和之前被转换的字符串相等与否
String temp=format.format(date);
System.out.println(str.equals(temp));
//得到时间:多少毫秒,从 1970-01-01 00:00:00 000 开始
long time=date.getTime();
System.out.println(time);
}
catch (Exception ex)
{
}
}
}
Q:给出两个日期字符串,判断两个日期之间有几个星期四,有几个零点。
A:一种方法是将当前日期每次都加一,然后检测当前日期是否是星期四。另一种方法是计算两个日期之间有几天,就对应有相应个零点。
public static int getThursday(String startStr,String endStr) throws Exception
{
DateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date start=format.parse(startStr);
Date end=format.parse(endStr);
Calendar calendar=Calendar.getInstance();
Date x=start;
int count=0;
calendar.setTime(x);
while (x.compareTo(end)<0)
{
//System.out.println(x+"--->"+calendar.get(Calendar.DAY_OF_WEEK));
if (calendar.get(Calendar.DAY_OF_WEEK)==Calendar.THURSDAY)
{
count++;
}
calendar.setTime(x);
calendar.add(Calendar.DATE,1);
x=calendar.getTime();
}
return count;
}
public static long getZeros(String startStr,String endStr) throws Exception
{
DateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date start=format.parse(startStr);
Date end=format.parse(endStr);
long diff=end.getTime()-start.getTime();
long zeros=diff/(24*60*60*1000);
if (startStr.split(" ")[1].equals("0:0:0"))
{
zeros--;
}
return zeros;
}
下面是Calendar类的一点源码
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Sunday.
*/
public final static int SUNDAY = 1;
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Monday.
*/
public final static int MONDAY = 2;
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Tuesday.
*/
public final static int TUESDAY = 3;
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Wednesday.
*/
public final static int WEDNESDAY = 4;
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Thursday.
*/
public final static int THURSDAY = 5;
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Friday.
*/
public final static int FRIDAY = 6;
/**
* Value of the {@link #DAY_OF_WEEK} field indicating
* Saturday.
*/
public final static int SATURDAY = 7;