Java 中的日期数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1801044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:46:27  来源:igfitidea点击:

Array of Dates in Java

javaarraysdate

提问by Madison

I know how to create an array of strings or integers, but how does one create an array of dates :/

我知道如何创建一个字符串或整数数组,但是如何创建一个日期数组:/

回答by OscarRyz

The same way you do for String and Int , you just place different types inside:

与对 String 和 Int 的处理方式相同,您只需在其中放置不同的类型:

Date [] dates = {
    new Date(), 
    new Date()
 };

Declared an array of size two with two dates.

声明了一个大小为 2 的数组,带有两个日期。

You can also initialize with null values:

您还可以使用空值进行初始化:

 Date [] dates = new Date[2];

Or add more significant values:

或者添加更重要的值:

 Date [] dates = {
    getDateFromString("25/11/2009"), 
    getDateFromString("24/12/2009")
 };

.... 
public Date getDateFromString( String s ) {
    Date result = ...// parse the string set the value etc. 
    return result;
}

EDIT

编辑

...but is there anyway you can finish up what you were doing in the getDateFromString method?

...但是无论如何你可以完成你在 getDateFromString 方法中所做的事情吗?

Sure, I didn't initially because my point was to show, that you could put anything that is of type "Date" there.

当然,我最初并没有这样做,因为我的意思是要表明,您可以在其中放置任何类型为“Date”的内容。

You just have to use the SimpleDateFormate.parse()method ( inherited from DateFormat class )

您只需要使用SimpleDateFormate.parse()方法(从 DateFormat 类继承)

  simpleDateFormatInstance.parse( "24/12/2009" ); // returns christmas 2009.

Here's a complete working sample:

这是一个完整的工作示例:

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import static java.lang.System.out;

public class DateArrayTest {

    private static final SimpleDateFormat dateFormat 
                   = new SimpleDateFormat("dd/MM/yyyy");
    private static final Date invalidDate = new Date(0);


    // test creating a date from a string.
    public static void main( String [] args ) { 
        Date [] randomDates = {
            fromString("01/01/2010"), // new year
            fromString("16/09/2010"), // 200 yrs Mex indepence 
            fromString("21/03/2010"), // uhhmm next spring?
            fromString("this/should/fail"), // invalid date.
        };

        for( Date date: randomDates ) {
            print( date );
        }
    }

    /**
     * Creates a date from the given string spec. 
     * The date format must be dd/MM/yyyy ie. 
     * 24 december 2009 would be: 24/12/2009
     * @return invalidDate if the format is invalid.
     */
    private static final Date fromString( String spec ) {
        try {
            return dateFormat.parse( spec );
        } catch( ParseException dfe ) {
            return invalidDate;
        }
    }
    private static final void print( Date date ) {
        if( date == invalidDate ) {
            out.println("Invalid date");
        } else {
            out.println( dateFormat.format( date ) );
        }
    }
}

回答by thecoop

you can use an array of java.util.Date(API docs are here)

您可以使用一组java.util.Date(API 文档在此处

Date[] dates = new Date[] {
    new Date(),
    new Date(),
};

You can create an array of any object type in java - all reference and primitive types

您可以在 java 中创建任何对象类型的数组 - 所有引用和原始类型

回答by ewg

Or you could use the Collections API and Calendar class,

或者你可以使用 Collections API 和 Calendar 类,

import java.util.*;

List<Calendar> dates = new ArrayList<Calendar>(5); // initial size
dates.add( Calendar.getInstance() );

回答by TofuBeer

You can consider (and this is not reality, but it sort of works this way) that primitives are something like this (I do get to reality later on... so keep reading):

你可以考虑(这不是现实,但它有点像这样)原语是这样的(我稍后会进入现实......所以继续阅读):

int.7, int.42 (won't compile) where int is a class (it is not) and 7 and 42 are public static final variables (they are not).

int.7, int.42(不会编译),其中 int 是一个类(不是),7 和 42 是公共静态最终变量(它们不是)。

and that Strings are something like this:

并且字符串是这样的:

String."Hello", String."world" (won't compile) where String is a class (it is) and "Hello" and "world" are public static final variables (they are not).

String."Hello", String."world" (不会编译)其中 String 是一个类(它是),“Hello”和“world”是公共静态最终变量(它们不是)。

If my fake reality were true you would have to have something like:

如果我的虚假现实是真的,你将不得不拥有类似的东西:

// again, won't compile.
public class int
{
    public static final int 7 = new int(7);
    public static final int 42 = new int(42);
    private final ??? data;

    public int(??? val)
    {
        data = val;
    }
}

and

// also will not compile
public class String
{
    public final String "Hello" = new String("Hello);
    public final String "world" = new String("world);
    private final ??? data;

    public String(final ??? val)
    {
        data = val;
    }
}

now you make a an array like (still won't compile):

现在你制作了一个像(仍然不会编译)的数组:

int[] array = new int[] { int.7, int.42 };
String[] array = new String[] {String."Hello", String."world" };

In the case of String my alternate reality would be very silly since it is impossible for the String class to know in advance every single possible String (for int it is possible).

在 String 的情况下,我的替代现实将非常愚蠢,因为 String 类不可能事先知道每个可能的 String(对于 int 是可能的)。

So we would get rid of the public static final variables in String and do this instead:

因此,我们将摆脱 String 中的公共静态最终变量,而是这样做:

String[] array = new String[] { new String("Hello"), new String("world") };

Now to reality:

现在回到现实:

When the java compiler, when it sees "Hello" or "world" it does something similar to "new String("Hello")" - it is a bit smarter so that if you have "Hello" 20 times in a file that there is only one copy (and some other things too).

当 java 编译器看到“Hello”或“world”时,它会做一些类似于“new String("Hello")”的事情——它更聪明一点,所以如果你在一个文件中有 20 次“Hello”只有一个副本(还有其他一些东西)。

When you say:

当你说:

new int[100]; you get an array of 100 ints all set to 0.
new String[100]; you get an array of 100 Strings all pointing to null.
new Data[100]; you get 100 Dates all pointing to null.

Since the String and the Date ones are pointing to null you need to allocate a new object for each one. The reason that you don't have to say "new" with String is that the compiler treats is specially. The reason you do not have to say "new" with int is that it is a primitive instead of an object.

由于 String 和 Date 指向 null,您需要为每个对象分配一个新对象。您不必对 String 说“new”的原因是编译器处理的是特殊的。你不必用 int 说“new”的原因是它是一个原始类型而不是一个对象。

So, the easy answer to your question is, you have to allocate a new Date for each element of the array :-)

因此,对您的问题的简单回答是,您必须为数组的每个元素分配一个新的 Date :-)

回答by Mohit Miglani

Did you mean inputting an array of dates.This code would help..

你的意思是输入一个日期数组。这段代码会有所帮助..

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();
    }
}