You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java输入MM/dd/yyyy格式日期仅输出对应星期几名称的实现问题

问题根因

你当前代码直接打印Date对象时,默认调用Date类的toString()方法,会输出包含星期简写、月份、具体时间、时区、年份的完整字符串,因此不符合仅输出星期全称的需求。

修改方案

方案1:沿用现有SimpleDateFormat逻辑(兼容Java 8之前版本)

新增一个专门用于格式化星期全称的SimpleDateFormat实例即可,其中格式符EEEE对应星期的全拼写法:

package assignment1;

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

public class Assignment1 {
    public static void main(String[] args) throws ParseException {
        Scanner input = new Scanner(System.in);
        // 原有的解析输入日期的格式化器
        SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy");
        // 新增:输出星期全称的格式化器,EEEE代表星期全拼
        SimpleDateFormat weekFormat = new SimpleDateFormat("EEEE");
        System.out.println("Enter Date (Month/Day/Year) :");
        String dinput = input.nextLine();
        Date date1 = null;
       
        if (dinput != null && dinput.trim().length() > 0) {
            date1 = inputFormat.parse(dinput);
            // 格式化后输出
            System.out.println(weekFormat.format(date1));
        } else {
            System.out.println("输入不能为空");
        }
    }  
}

方案2:Java 8及以上版本推荐使用java.time新时间API

旧版Date、SimpleDateFormat存在线程安全、设计不规范的问题,Java 8之后推出的java.time包是官方推荐的时间处理方案,实现代码如下:

package assignment1;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Scanner;

public class Assignment1 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        System.out.println("Enter Date (Month/Day/Year) :");
        String dinput = input.nextLine();

        if (dinput != null && !dinput.isBlank()) {
            LocalDate date = LocalDate.parse(dinput, inputFormatter);
            // 获取星期全称,Locale.US保证输出英文星期,如需中文替换为Locale.CHINA即可
            String weekFullName = date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US);
            System.out.println(weekFullName);
        } else {
            System.out.println("输入不能为空");
        }
    }
}

内容的提问来源于stack exchange,提问作者Yazan Yousef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 03:03:00