I’m trying to calculate the number of days between 2 dates. When I run this, it throws the catch (ParseException ex).
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
String date1 = "11/11/2020";
String date2 = "13/11/2020";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date_1 = dateFormat.parse(date1);
Date date_2 = dateFormat.parse(date2);
System.out.println(date_1);
System.out.println(date_2);
long numberOfDays = date_2.getTime() - date_1.getTime();
numberOfDays = TimeUnit.DAYS.convert(numberOfDays, TimeUnit.MILLISECONDS);
System.out.println(numberOfDays);
}
catch (ParseException ex)
{
System.out.println("error");
}
}
}
other than the catch, there are no errors, so I’m kind of lost.
Don't use Date. Try this.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String date1 = "11/11/2020";
String date2 = "13/11/2020";
LocalDate d1 = LocalDate.parse(date1,dtf);
LocalDate d2 = LocalDate.parse(date2,dtf);
long ndays = d1.datesUntil(d2).count();
System.out.println(ndays);
If you had printed the catched exception:
System.out.println("error: " + ex.getLocalizedMessage());
You would have seen:
error: Unparseable date: "11/11/2020"
The problem is in:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
change it to:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Since the provided dates are in that format.
If Java 8 is an option I'd recommend using the Time API.
Example:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main
{
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String date1 = "11/11/2020";
String date2 = "13/11/2020";
LocalDate firstDate = LocalDate.parse(date1, format);
LocalDate secondDate = LocalDate.parse(date2, format);
long days = ChronoUnit.DAYS.between(firstDate, secondDate);
System.out.println("Days between: " + days);
}
}
Just change this :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
to that :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
The date you are trying to parse 11/11/2020 does not match the date format you are trying to use dd-mm-yyyy
You can resolve problems like that on your own by printing out the stack trace inside catch :
ex.printStackTrace();
First, you have different formats in input dates and defined format. Therefore, you're getting a parsing exception.
Secondly, We can java.time.Duration class in Java8 for such calculation. Example:
public static void main(String[] args) throws ParseException {
String date1 = "11/11/2020";
String date2 = "13/11/2020";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Duration duration = Duration.between(format.parse(date1).toInstant(), format.parse(date2).toInstant());
System.out.println("Days between: " + duration.toDays());
}
Your pattern is incorrect.
You use:
new SimpleDateFormat("dd-mm-yyyy");
but you need use:
new SimpleDateFormat("dd/mm/yyyy");
because yours date's have "/" instead of "-"
Related
I am trying to get a list of months (actually the first days of those months) between two dates in Java but I am not getting the expected results.
The start date is "3/17/2020", the end date "3/17/2021" and the expected result is as follows:
"01-Mar-2020"
"01-Apr-2020"
"01-May-2020"
"01-Jun-2020"
"01-Jul-2020"
"01-Aug-2020"
"01-Sep-2020"
"01-Oct-2020"
"01-Nov-2020"
"01-Dec-2020"
"01-Jan-2021"
"01-Feb-2021"
"01-Mar-2021"
Here below is the code I am using:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
String date1 = "3/17/2020";
String date2 = "3/17/2021";
DateFormat formater = new SimpleDateFormat("MM/dd/yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(date1));
finishCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat formaterYd = new SimpleDateFormat("01-MMM-YYYY");
while (beginCalendar.before(finishCalendar)) {
// add one month to date per loop
String date = formaterYd.format(beginCalendar.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}
}
With the above code I am getting the following result:
"01-Jan-2020"
"01-Feb-2020"
"01-Mar-2020"
"01-Apr-2020"
"01-May-2020"
"01-Jun-2020"
"01-Jul-2020"
"01-Aug-2020"
"01-Sep-2020"
"01-Oct-2020"
"01-Nov-2020"
"01-Dec-2020"
Please help me understand the issue and suggest any solution for the same with java 7.
I recommend you do it using the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time. The java.util date-time API and SimpleDateFormat are outdated and error-prone. In case you are not using Java-8, you can still use Java-8 date-time API through ThreeTenABP library.
If you are doing it in Android and your Android API level is still not compliant with Java8, check Java 8+ APIs available through desugaring.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getDateList("3/17/2020", "3/17/2021"));
}
static List<String> getDateList(String strStartDate, String strEndDate) {
// Formatter for the input
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/u");
// Formatter for the output
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
// Parse strings to LocalDate instances
LocalDate startDate = LocalDate.parse(strStartDate, inputFormatter);
LocalDate endDate = LocalDate.parse(strEndDate, inputFormatter);
return Stream.iterate(startDate.withDayOfMonth(1), date -> date.plusMonths(1))
.limit(ChronoUnit.MONTHS.between(startDate, endDate.plusMonths(1)))
.map(date -> date.format(outputFormatter))
.collect(Collectors.toList());
}
}
Output:
[01-Mar-2020, 01-Apr-2020, 01-May-2020, 01-Jun-2020, 01-Jul-2020, 01-Aug-2020, 01-Sep-2020, 01-Oct-2020, 01-Nov-2020, 01-Dec-2020, 01-Jan-2021, 01-Feb-2021, 01-Mar-2021]
Using legacy API:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) throws ParseException {
// Test
System.out.println(getDateList("3/17/2020", "3/17/2021"));
}
static List<String> getDateList(String strStartDate, String strEndDate) throws ParseException {
// List to be populated and returned
List<String> dateList = new ArrayList<>();
// Formatter for the input
DateFormat inputFormatter = new SimpleDateFormat("M/d/yyyy");
// Formatter for the output
DateFormat outputFormatter = new SimpleDateFormat("dd-MMM-yyyy");
// Parse strings to LocalDate instances
Date startDate = inputFormatter.parse(strStartDate);
Date endDate = inputFormatter.parse(strEndDate);
// Calendar to start with
Calendar startWith = Calendar.getInstance();
startWith.setTime(startDate);
startWith.set(Calendar.DAY_OF_MONTH, 1);
for (Calendar calendar = startWith; calendar.getTime().getTime() <= endDate.getTime(); calendar
.add(Calendar.MONTH, 1)) {
dateList.add(outputFormatter.format(calendar.getTime()));
}
return dateList;
}
}
Output:
[01-Mar-2020, 01-Apr-2020, 01-May-2020, 01-Jun-2020, 01-Jul-2020, 01-Aug-2020, 01-Sep-2020, 01-Oct-2020, 01-Nov-2020, 01-Dec-2020, 01-Jan-2021, 01-Feb-2021, 01-Mar-2021]
Using java.time.LocalDate:
public static List<LocalDate> diff(LocalDate start, LocalDate end) {
return start
.datesUntil(end)
.filter(e -> e.getDayOfMonth() == 1)
.collect(Collectors.toList());
}
diff(LocalDate.now(), LocalDate.of(2020, 12, 20))
Output:
[2020-10-01, 2020-11-01, 2020-12-01]
You can use DateTimeFormatter string date to LocalDate and vice-versa.
EDIT
Using java 7 only (modified given code in question):
public static void main(String[] args) throws IOException {
String date1 = "3/17/2020";
String date2 = "3/17/2021";
DateFormat formater = new SimpleDateFormat("MM/dd/yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(date1));
finishCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat formaterYd = new SimpleDateFormat("dd-MMM-YYYY");
// mind this condition in while
while (beginCalendar.compareTo(finishCalendar) <= 0) {
Calendar tmp = (Calendar)beginCalendar.clone();
tmp.set(Calendar.DAY_OF_MONTH, 1);
String date = formaterYd.format(tmp.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}
Java7 soulution:
public static void main(String[] args) throws ParseException {
DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Date dateFrom = df1.parse("3/17/2020");
Date dateTo = df1.parse("3/17/2021");
final Locale locale = Locale.US;
DateFormat df2 = new SimpleDateFormat("MMM-yyyy", Locale.US);
List<String> months = getListMonths(dateFrom, dateTo, locale, df2);
for (String month : months)
System.out.println(month.toUpperCase(locale));
}
public static List<String> getListMonths(Date dateFrom, Date dateTo, Locale locale, DateFormat df) {
Calendar calendar = Calendar.getInstance(locale);
calendar.setTime(dateFrom);
List<String> months = new ArrayList<>();
while (calendar.getTime().getTime() <= dateTo.getTime()) {
months.add(df.format(calendar.getTime()));
calendar.add(Calendar.MONTH, 1);
}
return months;
}
Output:
MAR-2020
APR-2020
MAY-2020
JUN-2020
JUL-2020
AUG-2020
SEP-2020
OCT-2020
NOV-2020
DEC-2020
JAN-2021
FEB-2021
MAR-2021
This question already has answers here:
Java : Cannot format given Object as a Date
(7 answers)
converting UTC date string to local date string inspecific format
(3 answers)
Closed 4 years ago.
I am trying to convert current UTC time (time from my Linux server) using below code.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class UtcToIst {
public static void main(String[] args) {
List<String> timeZones = new ArrayList<String>();
String ISTDateString = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());
System.err.println("utcTime: " + utcTime);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
String formattedDate = formatter.format(utcTime);
Date ISTDate = sdf.parse(formattedDate);
ISTDateString = formatter.format(ISTDate);
timeZones.add(utcTime+ ","+ ISTDateString);
} catch(Exception e) {
e.printStackTrace();
}
for(String i: timeZones) {
System.out.println(i);
}
}
}
When I execute the code, I get the below exception:
utcTime: 05-11-2018 12:55:28
java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:310)
at java.text.Format.format(Format.java:157)
at UtcToIst.main(UtcToIst.java:21)
I see that the UTC time being fetched correctly as: 05-11-2018 12:55:28
But the code is unable to parse the string into IST(Indian Standard Time).
I am unable understand how can I fix the problem.
Could anyone let me know what is the mistake I am making here and how can I sort it out ?
This line is useless and causes the error (utcTime is not a Date, it's a String).
String formattedDate = formatter.format(utcTime);
Just replace:
String formattedDate = formatter.format(utcTime);
Date ISTDate = sdf.parse(formattedDate);
With:
Date ISTDate = sdf.parse(utcTime);
Whole class:
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class UtcToIst {
public static void main(String[] args) {
List<String> timeZones = new ArrayList<String>();
String ISTDateString = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());
System.err.println("utcTime: " + utcTime);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
Date ISTDate = sdf.parse(utcTime);
ISTDateString = formatter.format(ISTDate);
timeZones.add(utcTime+ ","+ ISTDateString);
} catch(Exception e) {
e.printStackTrace();
}
for(String i: timeZones) {
System.out.println(i);
}
}
}
use LocalDateTime instead
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
Note:the #Benoit's answer produce the incorrect time result if the server timezone is not Indian timezone, Should set timezone to Indian explicitly.
First: Set correct timezone on SimpleDateFormat, Asia/Kolkata for Indian time.
Second: use utc formatter to parse the formatted time string to get the utc time instance.
Last: use Indian to format the utc time instance.
See below code:
SimpleDateFormat utcFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = utcFormatter.format(new Date());
System.err.println("utcTime: " + utcTime);
Date utcTimeInstance = utcFormatter.parse(utcTime);
SimpleDateFormat indianFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
indianFormatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String indianTime = indianFormatter.format(utcTimeInstance);
System.err.println("indianTime: " + indianTime);
On my pc prints:
utcTime: 05-11-2018 13:42:31
indianTime: 05-11-2018 19:12:31
I cannot format a date.
dateFormat.format() accepts a Date as argument. So I created a new Date()
It says the below Date() method is deprecated, and I get the below exception while running.
exception:
Exception in thread "main" java.lang.IllegalArgumentException at
java.util.Date.parse(Date.java:598)
public class MyDate {
public static void main(String[] args) {
Date date = new Date("2012-02-16T00:00:00.000-0500");
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate); // how do I test this conversion??
}
}
My database has date of the format - 2012-02-16T00:00:00.000-0500
I need to convert it to string of the format : dd-MMM-yyyy HH:mm:ss
I'm using Java6
Thanks to #Andy Brown. In addition to what Andy Brown has answered, I'm posting the complete snippet
Complete Solution:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SampleDate {
public static void main(String[] args) throws ParseException {
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-03-16T00:00:00.000-0500");
String strDate = parseFormat.format(date);
System.out.println(strDate);
// if you get date of type 'java.sql.Date' directly from database cursor like
//rs.getDate("created_date"), just pass it directly to format()
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate);
}
}
/*
Output:
2012-03-16T01:00:00.000-0400
16-Mar-2012 01:00:00
*/
you can also convert java.util.Date to java.sql.Date like this,
String dateString = "03-11-2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = dateFormat.parse(dateString);
java.sql.Date sqlDate = new Date(date.getTime());
// set the input param type as OracleTypes.DATE and pass the input param date as sqlDate
If you want to read in the date "2012-02-16T00:00:00.000-0500" you should probably use a SimpleDateFormat to parse it like so:
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-02-16T00:00:00.000-0500");
Along with the rest of your code this writes:
16-Feb-2012 05:00:00
The parse format pattern letters are listed in the SimpleDateFormat documentation. The T is escaped with apostrophes.
This answer assumes Java 7, or you would be using the new date & time API from Java 8
I have this string: 7 -Jun- 2014.
I want to convert to java.utils.Date;
I use this Code
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
but I get this exception :
java.text.ParseException: Unparseable date: "7-Jun-2013"
at java.text.DateFormat.parse(Unknown Source)
at ma.abcsolution.util.Test.main(Test.java:15)
try using
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
the SimpleDateFormat look at the given string like it you tell it to, so in your example it look for a string with 2 chars for days, followed by a '/' sign and then 2 chars for month and so on
Using SimpleDateFormatter you can convert from date string to date and date to date String
public final class DateUtil {
private static final String DEFAULT_DATE_FORMAT = "dd-MMM-yyyy";
private DateUtil() {
}
public static final String formatDate(final Date date, final String dateFormat) {
DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
return format.format(date);
}
public static final Date formatDate(final String date) throws ParseException {
return formatDate(date, DEFAULT_DATE_FORMAT);
}
public static final Date formatDate(final String date, final String dateFormat) throws ParseException {
DateFormat format = new SimpleDateFormat(dateFormat);
return format.parse(date);
}
}
Whenever you are going yo format date please verify the format you are using
In your case you used dd/MM/yyyy but date you used in format dd-MMM-yyyy.
Use
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
to format the date. You used the wrong format with the / signs.
See also:
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date date = new SimpleDateFormat("d-MMM-yyyy").parse("7-Jun-2014");
Use this code. It is simple.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTime {
public static void main(String args[]){
SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
Date date=new Date(dateInString);
System.out.println(ft.format(date));
}
}
I want to convert 3/13/2014 11:38:58 AM string to date format.
I see some examples but and also implement but I don't know how to convert AM/PM to 24 hour time format.
How to make it possible ?
Use SimpleDateFormat
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(string);
Using this you can convert your date and time..
SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
Date date_current = new Date();
Date date_start = null;
date_start = sdf.parse("3/13/2014 11:38:58 AM");
System.out.println("now time is.." + date_start);
Thanks..
Parsing Strings into Dates:
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " Parses as ");
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("Unparseable using " + ft);
}
}
}