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.
Related
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.
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.
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));
I have a date column in a Cassandra column family. When I retrieve data from this CF using datastax java API, this date object can be taken as a java.util.Date object.
It has a getYear() method but it is deprecated. The corresponding javadoc says:
As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
How can I get the year, month, day attributes from this date object properly?
Could you try like tihs;
// create a calendar
Calendar cal = Calendar.getInstance();
cal.setTime(datetime); //use java.util.Date object as arguement
// get the value of all the calendar date fields.
System.out.println("Calendar's Year: " + cal.get(Calendar.YEAR));
System.out.println("Calendar's Month: " + cal.get(Calendar.MONTH));
System.out.println("Calendar's Day: " + cal.get(Calendar.DATE));
As mentioned in javadocs;
#Deprecated public int getYear() Deprecated. As of JDK version 1.1,
replaced by Calendar.get(Calendar.YEAR) - 1900. Returns a value that
is the result of subtracting 1900 from the year that contains or
begins with the instant in time represented by this Date object, as
interpreted in the local time zone. Returns: the year represented by
this date, minus 1900.
A good option is to use date format as follows:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
Date date = sdf1.parse(datetime);
String year = sdf2.format(date);
use LocalDate object in java8
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
To retrieve the date & time fields you can use this code:
DateFormat.getDateTimeInstance().getCalendar().get(DateFormat.MONTH_FIELD)
Just replace MONTH_FIELD with one somehting else like "DAY_OF_WEEK_FIELD" to retrieve the day of the week (I think '1' stands for monday) or "MINUTE_FIELD" for the current minute, etc. :)
I have verified that the date is read correctly from a file, but once I use SimpleDateFormat.format with the pattern "dd/MM/yy" it suddenly adds a month. This leads me to believe lenient mode is calculating the wrong value. But I have no idea what would make it add a full month.
Some example dates I read:
16/09/2013
23/09/2013
30/09/2013
07/10/2013
14/10/2013
21/10/2013
The code used to parse the date (it's a wrapper around Calendar I made):
public static SimpleDateTime parseDate(String date)
{
String[] dateParts = date.split("[-\\.:/]");
int day = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);
return new SimpleDateTime(dag, maand, jaar);
}
The constructor used here:
public SimpleDateTime(int day, int month, int year)
{
date = Calendar.getInstance();
date.setLenient(true);
setDay(day);
setMonth(month);
setYear(year);
}
The setters for day, month and year:
public void setYear(int year)
{
date.set(Calendar.YEAR, year);
}
public void setMonth(int month)
{
date.set(Calendar.MONTH, month);
}
public void setDay(int day)
{
date.set(Calendar.DAY_OF_MONTH, day);
}
And the code used to format the date:
public String toString(String pattern)
{
String output = new SimpleDateFormat(pattern, Locale.getDefault()).format(date.getTime());
return output;
}
where the pattern passed is:
"dd/MM/yy"
Intended to print a date as:
16/09/13
23/09/13
Instead I get:
16/10/13
23/10/13
January is 0 in Java; February is 1 and so on.
See Calendar.JANUARY, Calendar.FEBRUARY.
So when you're reading 1 from the file
you think you read JAN but you read FEB.
You should do: date.set(Calendar.MONTH, month-1); to fix this.
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
Calendar.MONTH
From documentation:
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY; the last depends on the number of months in a year.
So if you check JANUARY you see it starts in zero.
Make sure your month is in the interval 0-11. Possibly it is in 1-12.
The reason for this is that the counting starts at 0.
January == 0
February == 1
and so on. See the documentation.
THe problem is that you pass 9 to SimpleDateFormat and since month are indexed from 0 to 11 it will parse month '9' as the 10th month.
You need to subtract 1 from the month :)
Calendar class in Java holds months starting from 0, hence when you set the month as 0, it would consider it as January. SimpleDateFormat provides for a way to correctly display the value as 01.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 0);
System.out.println(new SimpleDateFormat("dd/MM/yy").format(cal.getTime()));
Output:
29/01/14
The workaround for you to align you file that Calendar can work with (since December - or 12 would trickle over to the next year) or modify your logic to pick Constants like:
cal.set(Calendar.MONTH, Calendar.JANUARY);
The answer by peter.petrov is almost correct, except for one major problem. Like your question, it neglects to account for time zone.
For your information, this kind of work is much easier in Joda-Time (or new java.time.* classes in Java 8). Joda-Time is so much cleaner you won't even feel the need to create a wrapper class.
// Specify the time zone for which the incoming date is intended.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Brussels" );
String input = "16/09/2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy").withZone( timeZone );
DateTime dateTime = formatter.parseDateTime( input );
String output = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "output: " + output );
System.out.println( "millis since Unix epoch: " + dateTime.getMillis() );
When run…
dateTime: 2013-09-16T00:00:00.000+02:00
output: 16/09/2013
millis since Unix epoch: 1379282400000