Home  >  Article  >  Java  >  Java implementation to determine the day of the week based on date

Java implementation to determine the day of the week based on date

王林
王林Original
2019-11-29 09:48:153156browse

Java implementation to determine the day of the week based on date

Knowledge Supplement:

SimpleDateFormat is a specific class that formats and analyzes data in a particularly sensitive way. It allows formatting (date -> text), parsing (text -> date) and normalization.

parseMethod: Parse the string type (java.lang.String) into the date type (java.util.Date).

Learning video sharing: java video tutorial

Examples are as follows:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTools {
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", 
        "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public static void main(String[] args) {
        System.out.println(DateTools.dateToWeek("2017-01-01"));
    }
}

java related article tutorials: java introduction

The above is the detailed content of Java implementation to determine the day of the week based on date. 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