Home  >  Article  >  Java  >  Java determines what day it is today

Java determines what day it is today

尚
Original
2019-11-22 15:19:316445browse

Java determines what day it is today

How to determine the day of the week in Java:

1. Use the Calendar class

 /**
     * 获取当前日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
       }

        return weekDays[w];
    }

The weekday above is the day of the week, but in Java The trick is weekday=1, the day is Sunday; weekday=2, the day is Monday;...; weekday=7, the day is Saturday.

This is different from JS in which 0 is Sunday, 1 is Monday, 2 is Tuesday,..., 6 is Saturday. Therefore, based on JS experience, similar programs in Java will go wrong. .

2. Use SimpleDateFormat to format the date

import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by zhisheng_tian on 2018/6/19
 */
public class FormatDateTime {
    public static void main(String[] args) {
        SimpleDateFormat myFmt3 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
        Date now = new Date();
        System.out.println(myFmt3.format(now));
  
    }
}

Output:

2018年06月19日 23时10分05秒 星期二

Note: The format string is case-sensitive

For creating SimpleDateFormat, pass in Parameters: EEEE represents the week, such as "Thursday"; MMMM represents the Chinese month, such as "November"; MM represents the month, such as "11";

yyyy represents the year, such as "2010"; dd represents Days, such as "25"

For more java knowledge, please pay attention tojava basic tutorial.

The above is the detailed content of Java determines what day it is today. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn