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
Related
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.
I have a string like this 210115 I want to represent it as 21:01:15 any ideas?.
I tried using Gregorian calendar but it adds date to it which I don't want
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
date = sdf.parse("210115");
}
catch(Exception e){
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());
Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15
Thanks.
To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.
In this case, it sounds like you might want to use something like
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );
So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.
LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format.
Simply do string operation as:
String time="210115";
String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
System.out.println(newtime);
you will get the required format.21:01:15
Let's have the following:
Date inDbDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
inDbDate = sdf.parse("2015-09-27 23:24:28.035");
Now, when I output the inDbDate I receive the following:
Sun Sep 27 23:24:28 EEST 2015
So, If I have two dates with millisecond differences, there would be no way to find out or to display it.
How do I compare two Dates with this format - 2015-09-27 23:24:28.035 ?
If you want to compare two Date variables, there are some methods provided after(), before(), equals().
private void someMethod(){
final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date firstDate = new Date();
Date secondDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
firstDate = sdf.parse("2015-09-27 23:24:28.035");
secondDate = sdf.parse("2015-09-27 23:24:28.036");
} catch (ParseException pe) {
pe.getMessage();
}
if(firstDate.after(secondDate)) {
System.out.println("The first date is after the second date");
} else{
System.out.println("The first date is before the second date");
}
}
You can copy and paste the above method into your IDE, then try changing the time in the Date variables and see what the outcome is as well as changing the check performed in the if statement.
If you look at the values in one of the Date objects in your debugger you can see the milliseconds are there, just not shown when printed out in a certain format.
1/ you should parse inDbDate with date format ==> inDbDate = sdf.parse("2015-11-11 23:24:28.035");
2/ you can now compare the two dates
if (inDbDate.compareTo(new Date()) > 0) {
System.out.println("inDbDate is after the current date !!");
}
3/ if you want to display, you format it
System.out.println("current time = " + sdf.format(new Date()));
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.
I have My Database data in this format
18-NOV-10
I have to pass the same format into java.util.Date like this
Date date = new java.util.Date(dateformater);
so that the result of java.util.Date is like this 18-NOV-10
Is this possible ??
I tried this way
String strDate = "12-NOV-07";
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MMM-yy");
Date date = sdfSource.parse(strDate);
System.out.println(date);
But i am getting the result as "Mon Nov 12 00:00:00 IST 2007 " which i want it only
12-NOV-07"
You can use java.text.DateFormat (actually SimpleDateFormat) to get you where you want to go, but maybe you shouldn't be storing the dates as strings in your database. It will do output and parsing.
SimpleDateFormat sdf =
new SimpleDateFormat("DD-MMM-YY");
Date parsed = sdf.parse(dateString);
See http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/
Once you get the Date, you can turn it into the format you want but it will be held in memory as a Date object. You can get it in the form you want using
String dateString = sdf.format(parsed);
As others have pointed out, you should probably store your dates as dates, not strings; nevertheless...
If you want to turn a Date back into a string in that format you can use the following:
DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date date = new Date();
String dateStr = formatter.format(date); // Gives "22-May-11"
If you need MAY instead of May, just use toUpperCase() on the resultant string.
DateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
Date d = sdf.parse("18-NOV-10");
Try System.out.println(sdfSource.format(date).toUpperCase()); instead. The Date object will always have a time component to it; there is no way to "disable" that feature. What you can do instead is to ignore it in your calculations and display. If all Date objects you use are set to the same time of the day, then you can safely ignore the effect of the time component in your comparisons. If you look carefully, the time component of your Date object is set to midnight.