Date selector based on months in Java - java

I have code in Java for Selenium Webdriver TestNG. Is for comparing if the date on the website is same as today date.
Problem is that date on webpage dateOnWebpage for 11th April 2018 is in format
Today 4/11/2018
So I made selecter to compare date formats if months < 10 if(javaDateSelector < 10) than date to compare is in format M/dd/yyyy else is in format MM/dd/yyyy.
Is there better way to code it than I made it? Because I needed to parse date to string and than to int to compare it and code is quite long.
#Test(priority=3)
public void test3DateCheck() throws Exception
{
String dateOnWebpage = driver.findElement(By.xpath("//div[#id='homeCalendarSection']/div/div[2]/table/tbody/tr/td/div/ul/li")).getText();
System.out.println("Today Date on webpage is : " + dateOnWebpage);
//DateFormat dateFormat1 = new SimpleDateFormat("M/dd/yyyy");
DateFormat dateFormat1 = new SimpleDateFormat("MM");
Date date = new Date();
String javaDate1 = dateFormat1.format(date);
int javaDateSelector = Integer.parseInt(javaDate1);
if(javaDateSelector < 10)
{
DateFormat dateFormat2 = new SimpleDateFormat("M/dd/yyyy");
String javaDate2 = dateFormat2.format(date);
System.out.println("Today Date from Java is : " + javaDate2);
Assert.assertEquals(dateOnWebpage, "Today " + javaDate2);
}
else
{
DateFormat dateFormat3 = new SimpleDateFormat("MM/dd/yyyy");
String javaDate3 = dateFormat3.format(date);
System.out.println("Today Date from Java is : " + javaDate3);
Assert.assertEquals(dateOnWebpage, "Today " + javaDate3);
}
}

If you don’t care whether the date on the web page is written with leading zero for month and day of month or not and just want to test whether the date is correct:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("'Today' M/d/uuuu");
LocalDate today = LocalDate.now(ZoneId.of("Pacific/Norfolk"));
System.out.println("Today is " + today);
LocalDate observedDate = LocalDate.parse(dateOnWebpage, dateFormatter);
Assert.assertEquals(today, observedDate);
Rather than testing the string I am parsing the date and testing it. Even though the pattern has one M and one d in it, parsing two-digit months and two-digits day of month poses no problem.
If on the other hand you also want to test that the date on the web page is written without any leading zeroes, it’s best to test the string, like you already did:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/uuuu");
LocalDate today = LocalDate.now(ZoneId.of("Pacific/Norfolk"));
String todayString = today.format(dateFormatter);
System.out.println("Today is " + todayString);
Assert.assertEquals("Today " + todayString, dateOnWebpage);
Again, even though the pattern has one M and one d in it, two digits will be printed if the month or the day of month is greater than 9. What else could the format method do? If you require two-digit day of month always, put dd in the format pattern string.
In both snippets please fill in your desired time zone where I put Pacific/Norfolk since it is never the same date everywhere on the globe.
I am using and recommending java.time, the modern Java date and time API. DateFormat and SimpleDateFormat are not only long outdated, they are also notoriously troublesome. Date is just as outdated. I would avoid those classes completely. The modern API is generally so much nicer to work with.
Link: Oracle tutorial: Date Time explaining how to use java.time.

Related

Trouble with formatting a string that contains a date in java

Basically I have a string that includes a date and I am trying to have it print out a 0 infront of the months and days that only have 1 digit. so 1 would print out 01. This is the code I have written but i get an error that is saying : Exception in thread "main"java.util.IllegalFormatConversionException: d != java.lang.String.
day = String.format("%02d", day);
Assuming that day is an int
then with
day = String.format("%02d", day);
you are trying to re-assign a String to the int
try
String dayStr = String.format("%02d", day);
edit
So as day is already a String then format("%02d", day); will not work d means it is an int
So convert it to a int first
day = String.format("%02d", Integer.valueOf (day));
If I am allowed to take a step back: this may smell a bit like a design problem. You shouldn’t store your date in a string in dd/mm/yyyy format. You should store your date in a LocalDate. Of course, if the date is string input, for instance from the user, you need to accept is as such. Then convert to LocalDate:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String dateString = "1/9/2019";
LocalDate date = LocalDate.parse(dateString, dateFormatter);
For formatting the day of month into two digits use another DateTimeFormatter:
DateTimeFormatter dayOfMonthFormatter = DateTimeFormatter.ofPattern("dd");
String dayString = date.format(dayOfMonthFormatter);
System.out.println("Day in two digits is " + dayString);
Output in this case is:
Day in two digits is 01
Or to output the full date with two-digit day and two-digit month:
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String outputString = date.format(outputDateFormatter);
System.out.println("Output: " + outputString);
Output: 01/09/2019
Link: Oracle tutorial: Date Time.

How to add X number of days to current date and format as UTC

I'm trying to get the current date/time add a number of days and display in a UTC format.
Current output is like this: 2019-05-09T11:11:4226
See code for below, I think I'm maybe taking the wrong approach to this.
int NumDaysInFurure = 1;
Date currentDate = new Date();// get the current date
SimpleDateFormat daateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
daateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String date = ""+dateFormat.format(currentDate) + NumDaysInFurure;//add one day to the current date
Log.i("the future date is", date);
Starting from Java8, this would be a better approach:
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").format(LocalDateTime.now().plusDays(1))
to break it down:
LocalDateTime.now()
returns an instance of LocalDateTime with the current date and time.
You add one day (using the plusDays(Long days)) method.
The result of this, you format using a DateTimeFromatter.
The result of the complete is a String with the right date/format.

Query data between two dates

I need to get data between two dates from the Mongodb data that hosted in online server. I tried this code and it's working good in my Localhost (local data & live data). But when I uploaded the app in online and it's not working properly in Live.
The results are not accurate in live site. It fetches some records before and after the specified dates. For example, I give the dates 01-02-2018 and 28-02-2018, and the results are coming with records of 31-01-2018 and 01-03-2018.
I think the problem is dates are stored in UTC timezone ( 2018-02-15T23:33:30.000Z ).
Code:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date fromDate = format.parse(from + " 00:00:00");
Date toDate = format.parse(to + " 23:59:59");
Calendar cal = Calendar.getInstance();
cal.setTime(order.getOrderDate());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String strDate = sdf.format(cal.getTime());
Date orderDate = sdf.parse(strDate);
for(Order order : orders){
if(orderDate.after(fromDate) || orderDate.equals(fromDate) && orderDate.before(toDate) || orderDate.equals(toDate)){
//do something
}
}
java.util.Date doesn't have a timezone in it, so there's no point in parsing and formatting the order date. Formatting converts it to a String and parsing converts it back to a Date, which is pointless, because the order date is already a Date object.
You must set the timezone in the first formatter (the format variable), and then parse the from and to dates: they'll be set to the respective dates and times at Kolkata's timezone - in this case it's valid, because you have strings and want to convert them to dates.
Then you make your comparison using extra parenthesis to avoid any ambiguities (as pointed in the comments).
And there's no point in setting the Date to a Calendar, just to get it back later - the Calendar instance has no purpose in your code.
And the call to getOrderDate shouldn't be inside the for loop?
The full code will be like this:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
// from and to dates are from Kolkata's timezone, so the formatter must know that
format.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
// dates will be equivalent to this date and time in Kolkata, although
// the date itself doesn't store the timezone in it
Date fromDate = format.parse(from + " 00:00:00");
Date toDate = format.parse(to + " 23:59:59");
for(Order order : orders){
Date orderDate = order.getOrderDate();
// note the extra parenthesis, they make all the difference
if( (orderDate.after(fromDate) || orderDate.equals(fromDate)) &&
(orderDate.before(toDate) || orderDate.equals(toDate)) ) {
....
}
}
If you have Java >= 8, it's better to use the java.time API:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZonedDateTime fromDate = LocalDate
// parse "from" string
.parse(from, fmt)
// start of day at Kolkata timezone
.atStartOfDay(zone);
ZonedDateTime toDate = LocalDate
// parse "to" string
.parse(to, fmt)
// get start of next day
.plusDays(1).atStartOfDay(zone);
// convert the Date to ZonedDateTime
for (Order order : orders) {
ZonedDateTime orderDate = order.getOrderDate().toInstant().atZone(zone);
if ((orderDate.isAfter(fromDate) || orderDate.isEqual(fromDate)) && (orderDate.isBefore(toDate))) {
...
}
}
It's a different code because this API introduces new types and concepts, but it's quite a improvement from the previous API (Date and Calendar are messy, buggy and outdated).
Take some time to study this API, it's totally worth it: https://docs.oracle.com/javase/tutorial/datetime/

Reformatting a Date from DD-MMM-YYYY to YYYYDDMM or YYYYMMDD

I'm trying to use Java 8 to re-format today's date but I'm getting the following error:
java.time.format.DateTimeParseException: Text '09-OCT-2017' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor:
{WeekBasedYear[WeekFields[SUNDAY,1]]=2017, MonthOfYear=10, DayOfYear=9},ISO of type java.time.format.Parsed
Code:
public static String formatDate(String inputDate, String inputDateFormat, String returnDateFormat){
try {
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(inputDateFormat).toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(inputDate, inputFormatter);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(returnDateFormat);
String formattedString = localDate.format(outputFormatter);
return formattedString;
} catch (DateTimeParseException dtpe) {
log.error("A DateTimeParseException exception occured parsing the inputDate : " + inputDate + " and converting it to a " + returnDateFormat + " format. Exception is : " + dtpe);
}
return null;
}
I previously tried using SimpleDateFormat, but the problem is my inputDateFormat format is always in uppercase DD-MMM-YYYY, which was giving me incorrect results, so I tried using parseCaseInsensitive() to ignore the case sensitivity.
In the comments you told that the input format is DD-MMM-YYYY. According to javadoc, uppercase DD is the day of year field, and YYYY is the week based year field (which might be different from the year field).
You need to change them to lowercase dd (day of month) and yyyy (year of era). The parseCaseInsensitive() only takes care of the text fields - in this case, the month name (numbers are not affected by the case sensitivity - just because the month is in uppercase, it doesn't mean that the numbers patterns should also be).
The rest of the code is correct. Example (changing the format to yyyyMMdd):
String inputDate = "09-OCT-2017";
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
// use "dd" for day of month and "yyyy" for year
.appendPattern("dd-MMM-yyyy")
.toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(inputDate, inputFormatter);
// use "dd" for day of month and "yyyy" for year
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String formattedString = localDate.format(outputFormatter);
System.out.println(formattedString); // 20171009
The output of the code above is:
20171009
Regarding your other comment about not having control over the input pattern, one alternative is to manually replace the letters to their lowercase version:
String pattern = "DD-MMM-YYYY";
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
// replace DD and YYYY with the lowercase versions
.appendPattern(pattern.replace("DD", "dd").replaceAll("YYYY", "yyyy"))
.toFormatter(Locale.ENGLISH);
// do the same for output format if needed
I don't think it needs a complex-replace-everything-in-one-step regex. Just calling the replace method multiple times can do the trick (unless you have really complex patterns that would require lots of different and complex calls to replace, but with only the cases you provided, that'll be enough).
I hope I got you right.
Formatting a String to LocalDate is acutally pretty simple. Your date format is that here right 09-Oct-2017?
Now you just need use the split command to divide that into a day, month and year:
String[] tempStr = inputDate.split("-");
int year = Integer.parseInt(tempStr[2]);
int month = Integer.parseInt(tempStr[1]);
int day = Integer.parseInt(tempStr[0]);
After that it´s pretty easy to get that to LocalDate:
LocalDate ld = LocalDate.of(year, month, day);
I hope that helps.

How to Set Date to JdateChooser in java?

enter image description here
I used java Jcalender_1.4.jar
I have date like this,
String date = "13 Oct 2016";
i want this date set to JdateChooser text box,
by using this command JdateChooser.setDate();
how to covert string in to date format ?
You can do it using this easily by SimpleDateFormat command
String date = "13 Oct 2016";
java.util.Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
JdateChooser.setDate(date2);
and also you can use any date format.
Calendar ca = new GregorianCalendar();
String day = ca.get(Calendar.DAY_OF_MONTH) + "";
String month = ca.get(Calendar.MONTH) + 1 + "";
String year = ca.get(Calendar.YEAR) + "";
if (day.length() == 1) {
day = "0" + day;
}
if (month.length() == 1) {
month = "0" + month;
}
String dd = year + "-" + month + "-" + day;
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dd);
jDateChooser1.setDate(date);
try this set date form computer date
The following was first written as an answer to this duplicate question. I thought it would be better to have it here so we have all the answers in one place.
The following should work overall, only the details depend on the format of the dates in the JTable (from the other question). I have assumed that from the JTable you get a string like 03/07/2018 (I am told that this format would be commonplace in Portugal). In this case the following formatter will be fine for parsing it. If the string is in a different format, the formatter will have to be different too.
DateTimeFormatter dtfFormatador = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("pt-PT"));
LocalDate data = LocalDate.parse(getData, dtfFormatador);
Instant instante = data.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date dateAntiquado = Date.from(instante);
jdcSeletorDeDatas.setDate(dateAntiquado);
Unfortunately JDateChooser.setDate() requires an old-fashoined Date object, while we’d have preferred to avoid that outdated class. I am using a DateTimeFormatter for parsing the string from the JTable into a LocalDate and converting it to Date. LocalDate is the class from java.time, the modern Java date and time API, that we should use for a date without time of day.
Edit: harsha, your string was
String date = "13 Oct 2016";
To parse a string in this format, use the following formatter:
DateTimeFormatter dateFormatter= DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
Otherwise use the code above, where jdcSeletorDeDatas is the JDateChooser.
Link: Oracle tutorial: Date Time explaining how to use java.time.
try {
String date = "13 Oct 2016";
Date date2 = new SimpleDateFormat("dd MMM yyyy").parse(date);
jDateChooser2.setDate(date2);
} catch (Exception e) {
System.out.println(e);
}
Right Click on JDateChooser
Go to Properties
Change dateFormatString as "dd MMM yyyy"
Try to cast the value to the Date type. This Worked for me:
int SelectRow = jTable1.getSelectedRow();
jDateChooser1.setDate((Date) jTable1.getModel().getValueAt(SelectRow, 2));

Categories

Resources