如何在Java中设置日期输入?

8

有没有直接的方法将日期设置为变量,而作为输入呢?我的意思是,在设计时我不知道日期,应该由用户提供。我尝试了下面的代码,但它不起作用:

Calendar myDate = new GregorianCalendar(int year, int month, int day);


1
查看Scanner类以处理用户输入。 - Alexis C.
1
我不明白你所说的“直接将日期设置为变量但作为输入”的意思。你能具体说明一下吗? - kingspeech
1
我的意思是,如果Java定义了一个方法,它将参数作为变量,并在运行时知道它们的值。 - user3159060
3
请注意,GregorianCalendar 类已被标记为过时的类,Java 8 及更高版本中应使用 ZonedDateTime 替代。如果您只需要年月日而不需要时间,则可以使用 LocalDate。例如,LocalDate.of(2018, 1, 23) 表示2018年1月23日。 - Basil Bourque
9个回答

10

简而言之

 LocalDate.of( 2026 , 1 , 23 )  // Pass: ( year , month , day )

java.time

一些其他答案在展示如何从用户那里获取输入时是正确的,但使用麻烦的旧日期时间类,这些类现已被java.time类所取代。

LocalDate

对于仅包含日期而不包含时间和时区的值,请使用LocalDate类。

LocalDate ld = LocalDate.of( 2026 , 1 , 23 );

根据此处讨论,将您的输入字符串解析为整数:如何在Java中将String转换为int?

int y = Integer.parseInt( yearInput );
int m = Integer.parseInt( monthInput );  // 1-12 for January-December.
int d = Integer.parseInt( dayInput );

LocalDate ld = LocalDate.of( y , m , d );

Table of date-time types in Java, both modern and legacy.


关于java.time

java.time框架已内置于Java 8及以后版本。这些类取代了老旧的遗留日期时间类,如java.util.DateCalendarSimpleDateFormat等。

Joda-Time项目现在处于维护模式,建议迁移到java.time类。

了解更多信息,请参阅Oracle教程。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

如何获取java.time类?

ThreeTen-Extra 项目扩展了 java.time 的附加类。该项目是 java.time 可能未来添加的试验场。您可能会在这里找到一些有用的类,例如 Interval, YearWeek, YearQuarter以及更多


9
尝试使用以下代码。我正在解析输入的字符串以创建一个日期。
// To take the input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Date ");

String date = scanner.next();

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date2=null;
try {
    //Parsing the String
    date2 = dateFormat.parse(date);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(date2);

1
这种方式是否能生成真实的日期?我的意思是,如果我输入了一个错误的日期,它会接受吗? - user3159060
1
是的!确实如此。请确保您以正确的格式输入日期。我的意思是对于上面的例子, 如果我输入:35-MAR-1992 那么结果将是:Sat Apr 04 00:00:00 PST 1992 - sitakant
1
请注意,一些令人烦恼的旧日期时间类(如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat)已被标记为遗留系统,并被内置于 Java 8 和 Java 9 的 java.time 类所取代。详见Oracle官方教程 - Basil Bourque

3

java.time

我建议您在处理日期时使用现代的 Java 日期和时间 API,即 java.time。其他答案中使用的 DateSimpleDateFormat 类设计不佳且过时,不要使用它们。

此外,我建议用户使用特定于其语言环境的短格式输入日期。为此,我首先声明了一些常量:

private static final Locale defaultFormattingLocale
        = Locale.getDefault(Locale.Category.FORMAT);
private static final String defaultDateFormat = DateTimeFormatterBuilder
        .getLocalizedDateTimePattern(FormatStyle.SHORT, null, 
                IsoChronology.INSTANCE, defaultFormattingLocale);
private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern(defaultDateFormat, defaultFormattingLocale);

现在提示和读取日期的方法如下:
    Scanner inputScanner = new Scanner(System.in);
    
    LocalDate sampleDate
            = Year.now().minusYears(1).atMonth(Month.NOVEMBER).atDay(26);
    System.out.println("Enter date in " + defaultDateFormat
            + " format, for example " + sampleDate.format(dateFormatter));
    String dateString = inputScanner.nextLine();
    try {
        LocalDate inputDate = LocalDate.parse(dateString, dateFormatter);
        System.out.println("Date entered was " + inputDate);
    } catch (DateTimeParseException dtpe) {
        System.out.println("Invalid date: " + dateString);
    }

美国本地化的示例会话:

Enter date in M/d/yy format, for example 11/26/20
2/9/21
Date entered was 2021-02-09

丹麦语环境下的示例会话:

Enter date in dd/MM/y format, for example 26/11/2020
9/februar/2021
Invalid date: 9/februar/2021

在最后一种情况下,您可能希望允许用户重试。我会留给您来处理。
链接 Oracle教程:日期时间介绍如何使用java.time。

3
不错!针对未来的访问者: 在上面给出的代码中,与 dateFormatter 一起使用的 Locale 不一定要与获得 defaultDateFormatLocale 相同。例如,String format = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.FULL, null, IsoChronology.INSTANCE, Locale.FRANCE); LocalDate now = LocalDate.now(); System.out.println(now.format(DateTimeFormatter.ofPattern(format, Locale.ENGLISH))); System.out.println(now.format(DateTimeFormatter.ofPattern(format, Locale.FRANCE))); - Arvind Kumar Avinash

2
也许你可以尝试一下我简单的以下代码:
SimpleDateFormat dateInput = new SimpleDateFormat("yyyy-MM-dd");
Scanner input = new Scanner(System.in);

String strDate = input.nextLine();

try
{
   Date date = dateInput.parse(strDate);
   System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
} 
catch (ParseException e) 
{
   System.out.println("Parce Exception");
}

2
感谢您想要做出贡献。请不要教年轻人使用早已过时且臭名昭著的 SimpleDateFormat 类。至少不要将其作为第一选择。而且不要没有任何保留地使用它。我们在 java.time, 现代 Java 日期和时间 API, 和它的 DateTimeFormatter 中有更好的选择。 - Ole V.V.

2
检查一下这个 :)
 ZoneId defaultZoneId = ZoneId.systemDefault();
 Scanner scanner = new Scanner(System.in);

 System.out.print("Enter the DOB: ");
 String dobString = scanner.nextLine();

 LocalDate dobLocal = LocalDate.parse(dobString);
 Date dob = Date.from(dobLocal.atStartOfDay(defaultZoneId).toInstant());
 System.out.println(dob);

简单的项目GitHub仓库:https://github.com/lojithv/Java-Enter-Student-Details.git

enter image description here

你应该像这样输入出生日期:年-月-日。
完成了:)

1
我修改了@SK08的答案,并创建了一个方法,该方法从用户输入中获取年份、月份和日期,并返回日期。
    Scanner scanner = new Scanner(System.in);
    String str[] = {"year", "month", "day" };
    String date = "";

    for(int i=0; i<3; i++) {
        System.out.println("Enter " + str[i] + ": ");
        date = date + scanner.next() + "/";
    }
    date = date.substring(0, date.length()-1);
    System.out.println("date: "+ date); 

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    Date parsedDate = null;

    try {
        parsedDate = dateFormat.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return parsedDate;

1
这是一条评论的转载。我要给予Arvind Kumar Avinash完全的赞誉。@arvindkumaravinash “不错!对于未来的访问者:在上面提供的代码中,与dateFormatter一起使用的Locale并不一定与用于获取defaultDateFormat的Locale相同。例如,”
String format = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.FULL, null, IsoChronology.INSTANCE, Locale.FRANCE);
LocalDate now = LocalDate.now();
System.out.println(
        now.format(DateTimeFormatter.ofPattern(format, Locale.ENGLISH)));
System.out.println(
        now.format(DateTimeFormatter.ofPattern(format, Locale.FRANCE)));

对于美国人,请确保用US替换FRANCE,英国人使用UK等。以下是当前使用的国家列表。 https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html

此外,请务必单独导入所有必要的包,因为time*将无法工作。 因此,这些基本上是

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
import java.time.format.FormatStyle;
import java.time.chrono.IsoChronology;

我只是想让Arvind得到一些认可,并且提醒如果你不在法国,需要填写正确的国家。@arvind - oofalladeez343

0

这个可以运行,我试过了!

package javaapplication2;
//@author Ibrahim Yesilay
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JavaApplication2 {  
    public static void main(String[] args) throws ParseException {
    Scanner giris = new Scanner(System.in);        
        System.out.println("gün:");
        int d = giris.nextInt();
        System.out.println("ay:");
        int m = giris.nextInt();
        System.out.println("yil:");
        int y = giris.nextInt();
        String tarih;
        tarih = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);  
        System.out.println("Tarih : " + tarih); 
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date girilentarih = null;
        girilentarih = dateFormat.parse(tarih);
        System.out.println(dateFormat.format(girilentarih));      
    }   
}

0

这应该可以正常工作,你还可以使用setlenient函数验证日期-

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

public class Datinput {

    public static void main(String args[]) {
        int n;
        ArrayList<String> al = new ArrayList<String>();
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        String da[] = new String[n];
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        Date date[] = new Date[n];
        in.nextLine();
        for (int i = 0; i < da.length; i++) {
            da[i] = in.nextLine();
        }
        for (int i = 0; i < da.length; i++) {

            try {
                date[i] = sdf.parse(da[i]);
            } catch (ParseException e) {

                e.printStackTrace();
            }
        }

        in.close();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接