user3334940
user3334940

Reputation: 3

Use of Date(); not giving current date

I am trying to display the current date on my Android application (4.2.2), Eclipse Luna (4.4.0). In the following code, I am getting an error for using Date(), saying that I must add an argument. However, the addition of 0 or long of course results in the date of Dec 31 1969 7:00.

 final DateFormat dateTimeFormatter = DateFormat.getDateTimeInstance();

 graph.setCustomLabelFormatter(new CustomLabelFormatter(){
    @Override
    public String formatLabel(double value, boolean isValueX) 
    {
        if (isValueX)
        {
        return dateTimeFormatter.format(new Date(0)); //how to append date to value
        }
        return null; //graphview generates Y-axis label
        }
     });

Is Date() still valid to use as obtaining the current date?

Upvotes: 0

Views: 2192

Answers (5)

kjonach
kjonach

Reputation: 154

It depends on whether you are importing "java.util.Date" or "java.sql.Date". The one for SQL requires a value in the constructor.

Eclipse will pop up a dialog asking you which Date you want to import. You may have selected the wrong import. IF that's the case, simply clear the "import" at the top of your file and try again, using "java.util.Date"

Upvotes: 0

pfranza
pfranza

Reputation: 3367

You are using the epoch date constructor (passing a specific time 0ms past epoch) so the correct output is in fact Dec 31 1969 7:00.

If you use the default constructor new Date() it will default to System.currentTimeMillis() and give you the current timestamp.

Additionally ensure you are using java.util.Date and not java.sql.Date

Upvotes: 1

James Baxter
James Baxter

Reputation: 1246

Take the zero out of the constructor! Otherwise it gets interpreted as milliseconds since the epoch beginning of 1970)

Yes, 'new Date()' is perfectly valid to get the current date/time.

SirKuryaki is correct that you have the wrong import (should not be java.sql.Date).

Reference: http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html

Reference: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date()

Upvotes: 1

Nyx
Nyx

Reputation: 2243

The constructor Date(long timestamp) takes in a long which is the milliseconds since the epoch (01 Jan 1970 00:00:00 GMT) and gives you a date object for it. Passing in 0, will therefore give you the epoch.

Simply call new Date(System.currentTimeMillis()) to get the current date!

Edit:

It is odd that you cannot use new Date() without any arguments, as the documentation clearly states that is is available (http://developer.android.com/reference/java/util/Date.html#Date()). Perhaps your project is miconfigured

Upvotes: 1

Ariel Carbonaro
Ariel Carbonaro

Reputation: 1539

I think you have the wrong import, make sure you have this line at the beginning of the file

import java.util.Date;

then you can call new Date() http://developer.android.com/reference/java/util/Date.html

Upvotes: 0

Related Questions