在Java中日期的数组 [英] Array of Dates in Java

查看:159
本文介绍了在Java中日期的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在弦乐和Int做同样的方式,您只需将不同类型内:

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

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

声明大小为2的阵列,两个日期。

Declared an array of size two with two dates.

您也可以初始化空值:

 Date [] dates = new Date[2];

或添加更多显著值:

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

修改

...但反正是有就可以完成了,你在getDateFromString方法在做什么?

当然,我最初没有因为我的观点是要表明,你可以把任何类型为日期那里。

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

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

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

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

这篇关于在Java中日期的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆