java date and time from timestamp - java

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

You can solve it this way:
dt[i] = sdfDate.parse(strDate);

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.

Related

How can i enter current date and time in textbox

I want to enter the current date and time along with second in a text box ; How can I do that ?
The code what I have written is as below , but it is only entering the string value what I am passing in send keys , which is clearly indicating I am not in correct track .
Any suggestion ?
// Create object of SimpleDateFormat class and decide the format
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy ");
//get current date time with Date()
Date date = new Date();
// Now format the date
String date1= dateFormat.format(date);
// Print the Date
System.out.println(date1);
collection_title.sendKeys("date1");
In collection_title.sendKeys("date1"); you are not using your variable date1, you are using the String "date1" - there should be no quotes around date1.
It should work like this:
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
Maybe you should try to use LocalDateTime.now() or Calender.getInstance() instead of new Date(), because the Date API methods are flawed and deprecated.

String to Date Conversion and Date arithmetic

I have a list of strings in my java application that represent dates. The format is yyyy/MM/dd. I want to be able to take all of these strings and convert them to actual date objects so arithmetic can be performed on them.
Basically I want to go through the list and remove dates that have already occurred. I have attached the code.
List<String> datesList = new ArrayList<String>();
datesList.add("2011-11-01");
datesList.add("2015-11-01");
//Get todays date and format it
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
//This string will also need to be converted to a date object so the loop arithmetic can be performed.
String today = formatter.format(currentDate.getTime());
System.out.println(today);
for(String date: datesList) {
//The list cannot change from a list of strings.
//So the conversion will probably have to take place in this loop.
System.out.println(date);
//if(date < today) ...
//datesList.remove(date);
}
Updating to include solution:
List<String> datesList = new ArrayList<String>();
datesList.add("2013-11-01");
datesList.add("2011-11-01");
datesList.add("2013-04-29");
datesList.add("2001-05-19");
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
List<String> validDatesList = new ArrayList<String>();
for(String date: datesList) {
Date listItem = formatter.parse(date);
Date todayDate = new Date();
if(todayDate.after(listItem)) {
System.out.println(listItem+" has already happened because today is "+todayDate);
} else{
validDatesList.add(date);
}
}
for(String validDate: validDatesList) {
System.out.println("Valid date: "+validDate);
}
Thanks.
Parse your Date's with this, and then you can compare the date with today's date
Date newDate = formatter.parse(date);
Date todayDate = new Date();
if(todayDate.after(newDate)) {
}
You can use a SimpleDateFormat object to parse a string into a Date object as well:
Date d = formatter.parse(today);, where today is your date in String format.
Then to check if the dare is after today, having gotten the current date as follows:
Date today = currentDate.getTime();
, your if statement would look like:
(if d.after(today)) {
datesList.remove(date);
A quite different and less efficient approach: add today's date to the list, sort the list, and remove all list items whose index is greater/smaller (depending on sort order) than today. Note that this will only work for the date format you specified ("yyyy-MM-dd") (with leading zeroes!) and only makes sense if removing previous dates is the only operation you'd like to do.
I would suggest you to convert date into long, then your work would be much easier.
Date d1 = new Date();//current time
d1.getTime()/1000;//will give you current time as a long value in second.
See epoch/unix time

How to get particular parts of a DateTime object?

I have a DateTime object DT which stores current time. When I print DT, I want it to only print the time part, ie HH-MM-SS (H = hours, M = minutes, S = seconds) and ignore the date part.
How can I do this ? For that matter, is it even possible to create a date time object which will only contain HH-MM-SS and nothing related to date ? If that is true, then I can simply print it instead of extracting the HH-MM-SS part.
Thanks.
If you only want the time, you should use a LocalTime instead of a DateTime. You can use DateTime.toLocalTime() to get the time part of an existing DateTime.
If you actually want to keep the DateTime but only reveal the time part when formatting, you can create a DateTimeFormatter with a pattern which only includes the time parts, but I'd usually consider this a design smell.
You can use Java date formatter which is in java.util.Date package.
Like :
Date todaysDate = new java.util.Date();
1. // Formatting date into yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
2. // Formatting date into yyyy-MM-dd e.g 2008-10-10
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
3. // Formatting date into MM/dd/yyyy e.g 10/10/2008
formatter = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = formatter.format(todaysDate);
With Java you can do it like this
Date obj = new Date() ;
System.out.println(new SimpleDateFormat("hh:mm:ss").format(obj)) ;
but it could be an expensive call.
But jodatime gives LocalTime which you can try out.

Simple java date conversion

Having some troubles and can't find a quick answer..
Im trying to store a date within a string, and later fetch it to convert it back to a date.
However when storing the date using:
string tmp = new Date().toString();
And then trying to convert it back using
Date date = new Date(tmp);
I get the Exception type
java.lang.IllegalArgumentException
with my Android 2.2 device. Does work with 2.2 & 2.3 emus tho.
Any tips on what other way i can store and convert back?
You could use SimpleDateFormat with its methods parse() and format().
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS");
String tmp = sdf.format(new Date());
Date date = sdf.parse(tmp);
Do you need it to be a string? long is easier :)
do
long time = new Date().getTime();
Date date = new Date(time);
then you dont' have to parse
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// to string
String dateStr = formatter.format(new Date());
// to date
Date date = formatter.parse(dateStr);
use SimpleDateFormat as shown below.
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
//this will convert date into string.
String temp = formatter.format(currentDate.getTime());
//this will convert string into date format.
Date date=(Date)formatter.parse(temp);

Date time object from webservice showing on Android textview with pattern?

Hi I have web service that return a date object like this as a return of the Json
"/Date(922312800000+0200)/"
However i need to show it on the textview in this pattern
"19.12.2011 16:15"
how can I convert that return to this pattern ?
Edit : Here is my code still giving java.lang.IllegalArgumentException
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateText = date.format(tempEntry.getCreatedDate());
Edit : Here is the code that work for me
String dateText = tempEntry.getCreatedDate();
String dateString = dateText.replace("/Date(", "").replace(")/", "");
String[] dateParts = dateString.split("[+-]");
Date dateFormat = new Date(Long.parseLong(dateParts[0]))
It appears to me that your Date is given in milliseconds from 1970, so, something like that:
// remove the unneeded information
String date = date.replace("/Date(", "").replace(")/");
String[] dateParts = date.split("[+-]")
//get the date represented by the given millis
Calendar c = Calendar.getInstance();
c.setTime(Long.parseLong(dateParts[0]);
// proceed with formatting to the desired date format.
You need to use: DateFormat.
Simple example:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
textView.setText("Today : " + today);

Categories