Question

I am working on android app with achartengine where I am making a TimeSeries linegraph. I have stored all my variables inside an Arraylist. Since I need correct date object to insert in the time axis of my chart I am using,

int count = list.size();
Date[] dt = new Date[count];
for(int i=0;i<count;i++){
    long a = Long.parseLong(list.get(i).get("time"));
    dt[i] = new Date(a);
}

Here long a has the timestamp . With above piece of code. I am able to get dt as 09-Apr-2014 but I need the date to be shown as 09-Apr 12:55 . How can I do that,

I tried using the folllowing

SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd HH:mm"); Date now = new Date(); String strDate = sdfDate.format(now);

But Since strDate is a string I cannot use it as dt[i] = strDate which will throws an error as one is Date and another is String.

How can I solve this ?

Thanks

Was it helpful?

Solution

You can solve it this way:

dt[i] = sdfDate.parse(strDate);

OTHER TIPS

If you really just need the date strings, you can do this:

int count = list.size();
String[] dt = new String[count];

for (int i = 0; i < count; i++) {
    long a = Long.parseLong(list.get(i).get("time"));
    Date d = new Date(a);
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
    dt[i] = dateFormat.format(d);
}

Or, if you actually need the Date array, just format the dates on the fly as you need them.

Your question is misguided - you are showing how you create Date objects in the code, yet what you want to fix is how you show them.
The Date array will have dates precisely to the millisecond. The default toString() method of the Date objects shows only the day, that's why you're not seeing the time.
It is inherently the UIs responsibility to decide on the format of time that it is going to print, hence you should pass the Date array to the UI (or up to the point of printing) and format them there.

The DateFormat can do both (date to string representation and back):

DateFormat formatter = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss" );

Date to String:

Date date = new Date();
String sDate = formatter.format( time );

String to Date:

Date date = formatter.parse(sDate );

When you store the date, you should store it as precise as possible (milliseconds). For displaying it as a string, you can use whatever format you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top