public static void main(String[] agrs) {
String newtime="2013-7-21";
System.out.print(testDate(newtime));
}
public static String testDate(String newtime) {
String dayNames[] = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
Calendar c = Calendar.getInstance();// 获得一个日历的实例
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
c.setTime(sdf.parse(newtime));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dayNames[c.get(Calendar.DAY_OF_WEEK)-1];
}
对于单双数日,能被2整除就是双数日,反之是单数日
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class $ {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
System.out.println(f.format(c.getTime()));
}
}
结果:
2013-07-30 11:57:46 星期二
如果你想单纯的获取星期,那么就用,余下的就好处理了
Format f = new SimpleDateFormat("E");
或者
System.out.println(c.get(Calendar.DAY_OF_WEEK));
得到的3,表示星期二。
import java.time.LocalDate;
import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
public class TemporalAdjustersEx{
public static void main(String[] args){
//接受
String input = args[0];
//设置要处理字符串的格式
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//将字符串转化为日期
LocalDate date = LocalDate.parse(input,format);
//获取星期几
DayOfWeek dotw = date.getDayOfWeek();
//打印
System.out.printf("%s is on a %s%n",date,dotw);
}
}
//Window下控制台运行
/*
javac TemporalAdjustersEx.java
java TemporalAdjustersEx 2018-04-19
2018-04-19 is on a THURSDAY
*/
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
SimpleDateFormat fmt = new SimpleDateFormat("dd MM yyyy");
Date d = fmt.parse(day+" "+month+" "+year);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int weekDay = cal.get(Calendar.DAY_OF_WEEK);
switch(weekDay) {
case 1 : System.out.println("SUNDAY"); break;
case 2 : System.out.println("MONDAY"); break;
case 3 : System.out.println("TUESDAY"); break;
case 4 : System.out.println("WEDNESDAY"); break;
case 5 : System.out.println("THURSDAY"); break;
case 6 : System.out.println("FRIDAY"); break;
case 7 : System.out.println("SATURDAY"); break;
default: break;
}
用Calendar这个类,里面有相应的方法