如何在 Java 中查找一年中的哪一周、哪一月
Java 中的 Calendar 类提供了确定一年中的哪一周和一个月中的哪一周的方法。使用 WEEK_OF_YEAR 和 WEEK_OF_MONTH 等字段,您可以根据当前日期轻松找到此信息。
查找一年中的哪一周和哪一月
Java Calendar 类 是一个抽象类,它提供了在特定时刻和一组日历字段(如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等)之间进行转换的方法,以及用于操作日历字段(如获取下一周的日期)的方法。以下是关于日历的要点 -
此类还提供了用于在包外实现具体日历系统的附加字段和方法。
日历定义某些日历字段返回的值范围。
使用 setTime(d1) 方法 将日历对象 (cl) 设置为当前日期。然后使用 WEEK_OF_YEAR 和 WEEK_OF_MONTH 字段提取年份和月份的周数。
示例
以下示例显示年份和月份的周数 -
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Date d1 = new Date(); Calendar cl = Calendar. getInstance(); cl.setTime(d1); System.out.println("today is " + cl.WEEK_OF_YEAR+ "week of the year"); System.out.println("today is a "+cl.DAY_OF_MONTH + "month of the year"); System.out.println("today is a "+cl.WEEK_OF_MONTH +"week of the month"); } }
输出
today is 30 week of the year today is a 5month of the year today is a 4week of the month
查找当前周数并将一周添加到月份
Calendar 实例 (cal) 用于确定月份和年份的当前周数。方法 add(Calendar.WEEK_OF_MONTH, 1) 用于将一周添加到当前日期。最终输出显示添加一周后的日期,以及相应的年份和月份的周数。
示例
以下程序使用 SimpleDateFormat 格式化月份 −
import java.util.Calendar; public class GetWeekOfMonthAndYear { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("Current week of month is : " +cal.get(Calendar.WEEK_OF_MONTH)); System.out.println("Current week of year is : " +cal.get(Calendar.WEEK_OF_YEAR)); cal.add(Calendar.WEEK_OF_MONTH, 1); System.out.println( "date after one year : " + (cal.get(Calendar.MONTH) + 1)+ "-"+ cal.get(Calendar.DATE)+ "-"+ cal.get(Calendar.YEAR)); } }
输出
Current week of month is : 2 Current week of year is : 46 date after one year : 11-18-2016
java_date_time.html