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;