用calendar怎么写出日历
怎样显示当前日历
怎样显示当前日历
2016-11-09
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Wor3 {
/*.分析以下需求,并用代码实现:
(1)通过键盘录入日期字符串,格式(2015-10-20)
(2)输出该日期是星期几及这一年的第几天
(3)如输入:2015-10-20,输出"2015年-10月-20日 是 星期二,是 2015年的第 293 天"
*/
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入日期,如输入:2015-10-20");
String lineday=sc.nextLine();
//demo1(lineday);
//demo2(lineday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(lineday);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日,是E,是y中的第D天");
System.out.println(sdf1.format(d));
}
private static void demo2(String lineday) {
String []sarr=lineday.split("-");
int []arr=new int[sarr.length];
for(int i=0;i<sarr.length;i++){
arr[i]=Integer.valueOf(sarr[i]);
}
//System.out.println(Arrays.toString(arr));
Calendar c =Calendar.getInstance();
c.set(arr[0],( arr[1]-1), arr[2]);
System.out.println(c.get(Calendar.YEAR)+"年-"+(c.get(Calendar.MONTH)+1)+"月-"
+c.get(Calendar.DATE)+"日是"+getWeek(c.get(Calendar.DAY_OF_WEEK))+"是"
+c.get(Calendar.YEAR)+"年的第"+c.get(Calendar.DAY_OF_YEAR)+"天");
}
private static String getWeek(int week) {
String arr[]={"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
return arr[week];
}
private static void demo1(String lineday) throws ParseException {
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(lineday);
System.out.println(d);
SimpleDateFormat sdf1= new SimpleDateFormat("yyyy年-MM月-dd日 " +
" 是E,是y年的第D天");
System.out.println(sdf1.format(d));
}
}
精简版
package com.imooc;
import java.time.*;
public class CalendarTest
{
public static void main(String[] args)
{
LocalDate date=LocalDate.now();
int month=date.getMonthValue();
int today=date.getDayOfMonth();
date=date.minusDays(today-1);
DayOfWeek weekday=date.getDayOfWeek();
int value=weekday.getValue();
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
for(int i = 1; i < value;i++)
System.out.print(" ");
while (date.getMonthValue()==month)
{
System.out.printf("%3d",date.getDayOfMonth());
if (date.getDayOfMonth()==today)
System.out.print("*");
else
System.out.print(" ");
date=date.plusDays(1);
if (date.getDayOfWeek().getValue()==1)System.out.println();
}
if(date.getDayOfWeek().getValue()!=1)System.out.println();
}
}
举报