I need to work with dates and I wasn't sure how to go about that in Java since I have never done it before.
I am pulling dates from the Excel file and they can be retrieved in the Data format which would represent the date.
Ex:
2/1/2010
5/12/2011
8/15/2011
9/1/2011
9/1/2011
All my codes are pretty irrelvent to the question, but I am setting up a getter/setter method:
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
So my question is this, in what way when I am pulling the data from Excel:
temp.setDate((row.getCell(3).getDateCellValue());
I can set the limit so it only retrieves data from x amount of months. 8, 12, et.. from the last month/year displayed in the file, instead of going back all the way to 2010? I can provide more details if needed.
Edit: This is what I have now:
import java.util.Date;
Date date;
date = row.getCell(3).getDateCellValue();
It shows: Tue June 01 00:00:00
I don't care about Tuesday or 00:00:00, I just have a whole list of data and I only want to show x amount of months.
Edit: I figured it out. :)
The question is pretty vague, but if you are using Excel I have found it very beneficial to save the file as a 'filename.csv'. This format very easy to work with, it is comma delimited going across and newlines going down. If you are periodically checking the month, it would be easy to ensure that you only go x months backwards.
First you need to parse the dates accordingly using the SimpleDateFormat class. The result is a date object.
SimpleDateFormat df = new SimpleDateFormat( "M/d/yyyy" );
Date date = df.parse(row.getCell(3).getDateCellValue());
Then:
Calendar cal = Calendar.getInstance();
will return you an object ob type Calendar, where you can set the date by
cal.setTime(date);
Finally your loop reading the Excel file can determine according to the calendar object, if the date should be included / further processed by using:
int month = cal.get(Calendar.MONTH); // e.g. 11 for Nov
int year = cal.get(Calendar.YEAR); // e.g. 2011
You have to work with DateFormat.class fo parse the cell, or use a Calendar to put Day Month Year
EDIT
You can also use Calendar.class
final String[] tabDate = {"2/1/2010", "5/12/2011", "8/15/2011",
"9/1/2011", "9/1/2011"};
// Extract field's value
final Calendar c = Calendar.getInstance();
// Parse the list of stringDate
for (final String string : tabDate) {
System.out.println("Input string: " + string);
final String[] shortDate = string.split("/");
// Build Calendar
c.set(Integer.valueOf(shortDate[2]), Integer.valueOf(shortDate[0]),
Integer.valueOf(shortDate[1]));
// Extract date as you like
System.out.format("%25s : %d/%d/%d\t%s\n\n", c.getTime(),
c.get(Calendar.MONTH), c.get(Calendar.DATE),
c.get(Calendar.YEAR), c.getTimeInMillis());
}
Console :
Input string: 2/1/2010
Mon Mar 01 09:09:48 CET 2010 : 2/1/2010 1267430988109
Input string: 5/12/2011
Sun Jun 12 09:09:48 CEST 2011 : 5/12/2011 1307862588109
Input string: 8/15/2011
Thu Sep 15 09:09:48 CEST 2011 : 8/15/2011 1316070588109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109
Related
From the below java code I'm getting a month First & last dateTimestamp, but here i need last dateTimestamp as - "Mon Aug 31 23:59:59 IST 2015" instead of - "Mon Aug 31 00:00:00 IST 2015"?
Calendar cal = Calendar.getInstance();
int year = 2015;
int month = 07;
cal.set(cal.DATE,1);
cal.set(cal.YEAR,year);
cal.set(cal.MONTH, month);
String firstDate = (cal.getActualMinimum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("firstDate-->"+"\t"+firstDate);
String lastDate = (cal.getActualMaximum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("lastDate-->"+"\t"+lastDate);
DateFormat firstFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = firstFormat.parse(firstDate);
System.out.println("BeginDate Timestamp"+ "\t" + beginDate);
DateFormat secoundFormat = new SimpleDateFormat("dd/MM/yyyy");
Date endDate = secoundFormat.parse(lastDate);
System.out.println("endDate Timestamp"+ "\t" + endDate);
Output:->
firstDate--> 1/8/2015
lastDate--> 31/8/2015
BeginDate Timestamp Sat Aug 01 00:00:00 IST 2015
endDate Timestamp Mon Aug 31 00:00:00 IST 2015
Please help me if we have any solution.
If I understand your question, it looks as if you want to pass a year and month into a method, and get back the last day of the passed month.
I would suggest consider (in this order):
which jdk you use
configuration of calendar
configuration of timezone (maybe)
using jodatime
As of 1.8 many JodaTime-like features have been added to the jdk- e.g. see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html (If you arent using 1.8 you can use the joda lib, assuming your organization allows it)
Calendar.getInstance() gives a default TimeZone and a default Locale, which means the definitions of the running JVM. You may or may not need to consider this and implement more than just getInstance(). See API javadoc.
Assuming a Gregeorian Calendar (hey, you could be Bahaian and have 19 months in the year ...) , here is one partial implementation using JDK 1.7, JodaTime jar 2.2, validation-1.0.0.GA jar:
#Test
public void testDate() {
final String dateStringOfFirstDay = "1.7.2015";
final Date lastDayOfMonth = getLastDayOfMonth(dateStringOfFirstDay);
Assert.assertNotNull(lastDayOfMonth);
//more assertions ...
}
private Date getLastDayOfMonth(#NotNull String dateStringOfFirstDay) {
//further validation here necessary according to required date format
DateTime dt = DateTime.parse(dateStringOfFirstDay);
return dt.dayOfMonth().withMaximumValue().toDate();
}
The defintion of DateFormat/DateTimeFormat and further result assertions is left up to you.
Best of luck!
Guys I got a solution for my question!!!
I think it will help u too...
Calendar calendar = Calendar.getInstance();
int year=2015;
int month=7;
int date=31;
int hourOfDay=23;
int minute=59;
int second=59;
int milliSecond=999;
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.set(calendar.MILLISECOND, milliSecond);
System.out.println("Time from Calendar: "+calendar.getTime());
long timeInMilliSeconds=calendar.getTimeInMillis();
System.out.println("timeInMilliSeconds from calendar: "+timeInMilliSeconds);
Timestamp timestamp=new Timestamp(timeInMilliSeconds);
System.out.println(timestamp);
The above program gives the last date last timestamp in a selected month.
getTimeInMillis() takes the time from Jan 01, 1970 to current time in Milliseconds.
Using those milliseconds i'm getting the Timestamp.
Thank you for your help guys!!!
OutPut:->
Time from Calendar: Mon Aug 31 23:59:59 IST 2015
timeInMilliSeconds from calendar: 1441045799999
2015-08-31 23:59:59.999
I want to get 12 hour clock time from milliseconds.I tried as follows
public class GetTimeFormat{
static SimpleDateFormat format;
public static String convertDate(String dateformat,Long date){
format = new SimpleDateFormat(dateformat);
String formattedDate = format.format(date);
return formattedDate;
}
public static void main(String args[])
{
long cal=1386059340010l;
String dateString=convertDate("MMM dd,yyyy HH:mm:ss a", cal);
System.out.println(dateString);
}
}
The corresponding date for the above milliseconds is Tue Dec 03 13:59:00 IST 2013
So I thought I will get formatted date as Dec 03,2013 1:59:00 PM
but instead I am getting Dec 03,2013 13:59:00 PM
there is no need for am/pm in 24 hour clock and in 12 hour clock am/pm is required
But In my way I am getting time in 24 hour format + PM.
Can Any body tell me whats the mistake here?
Another question is why in ideone its showing Dec 03,2013 08:29:00 AM
Not only in ideone but I have checked many online compilers and every where its showing the same but in local machine time is different(13:59)
You need to use a lowercase h in your format pattern:
String dateString = convertDate("MMM dd,yyyy h:mm:ss a", cal);
You can see here for a full reference of format patterns, including an example that covers this specific case.
As an input I have Date object(for example, exDate=Fri Aug 01 00:00:00 EEST 2014) that must be formated. After the parsing of the date, I get wrong date.
SimpleDateFormat sdf = new SimpleDateFormat(
"dd-MMM-YYYY hh.mm.ss.SSSSSSSSS aa", Locale.ENGLISH);
String dateStart = sdf.format(exDate);
Date dateF = sdf.parse(dateStart);
dateStart will be equal to
01-Aug-2014 12.00.00.000000000 AM
and the resut, dateF will be equal to
Sun Dec 29 00:00:00 EET 2013
So, after the parsing of a string with date, the result is wrong.
Maybe, somebody know the source of the problem? Or another way to format date in another SimpleDateFormat?
The problem is the YYYY which means:
Y Week year;
The actual year, which is what you are looking for would be yyyy.
I really recommend that you go in the link above to see the full list.
You should also replace the milliseconds to .SSS as you can't get more precise than that.
I have a XMLGregorianCalendar that I would like to convert to a Java Date object, but when I try to covert this:
2013-11-19T00:00:00-00:00
I always get a date with the value a day behind.
Mon Nov 18 17:00:00 MST 2013
I just want a date object containing 11/19/2013.
As commented above, the result you're getting is right - it's the same moment in time. Midnight UTC is 5PM MST the day before. Perhaps you should look into why your time is in "-00:00" instead of "-07:00" (MST)... but in the meanwhile, I suppose you could try this:
public static void main(String... args) throws DatatypeConfigurationException {
XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-11-19T00:00:00-00:00");
Calendar c = xcal.toGregorianCalendar();
c.setTimeZone(TimeZone.getDefault());
Date d = c.getTime();
System.out.println(d);
}
prints out Tue Nov 19 00:00:00 EST 2013, and will work for other times of day, not just midnight.
I just did this,
Date startDate = new Date(request.getStartTime().getYear(), request.getStartTime().getMonth(), request.getStartTime().getDay(), 0, 0, 0);
I have a list which contains dates in format (MON-YYYY) in string format, I need to sort this list.The approach I have followed till now is reading the list and converting the string in date format and using compare option, but i am not getting the desired result
Code Snippet
List<String> abc = new ArrayList<String>();
List<Date> xyz = new ArrayList<Date>();
abc.add("JAN-2010");
abc.add("JAN-2011");
abc.add("APR-2013");
abc.add("NOV-2009");
try {
for (String abc1 : abc) {
Date date;
date = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH)
.parse(abc1);
xyz.add(date);
}
Collections.sort(xyz, new Comparator<Date>() {
public int compare(Date arg0, Date arg1) {
// return arg0.getDate().compareTo(o2.getDate());
return arg0.compareTo(arg1);
}
});
for (Date date1 : xyz) {
System.out.println("Sorted : " + date1);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
Output
Sorted : Sun Nov 01 00:00:00 IST 2009
Sorted : Fri Jan 01 00:00:00 IST 2010
Sorted : Sat Jan 01 00:00:00 IST 2011
Sorted : Mon Apr 01 00:00:00 IST 2013
Expected Output
NOV-2009
JAN-2010
JAN-2011
APR-2013
I am also not sure if the above code is perfect in performance perspective as converting the string and parsing would take a long time if I have thousands of dates in MON-YYYY format in the list.
Ok, I see you corrected the typo.
Now, remember you need to use a DateFormatter also when you present the data, in addition to when you parse it.
So please try this:
for (Date date1 : xyz) {
System.out.println("Sorted : " + new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH).format(date1));
}
You might want to make the SimpleDateFormat available to all methods of your class as a field.
Additional info: please be aware SimpleDateFormat is known to not be thread-safe. You can use ThreadLocal as one solution to that.
Good luck.
You've parsed your dateString to actual Date object. And java.util.Date can't be formatted. Only a String representation of that Date object can be got.
You need to change your comparator to compare your dateString format by internally converting the Strings to date.
If you are gonna sort the Date objects, you'll get the output you've got. Also, as mentioned by #darijan, change your logic in the comparator.
First i think it's better to have only one instance of SimpleDateFormat and always use this to parse your dates.
I also suggest to create this instance of SimpleDateFormat in front of your try block, so you solve your second problem and can use SimpleDateFormat.format(date) to parse your dates back to requested stringformat.