Java String to date parsing error, how to do it properly - java

I am interested to know if my code is correct and it doesn't have any issues. Date is taken from binary file, written as a string in such format YYYY-MM-DD/Hours-minutes-seconds example: 2022-01-23/12:00:00.
Program was meant to check date if it's expiring or expired, add it to proper list and display it after loops end.
public static void expiration_date(String filepath){
try {
DataInputStream read = new DataInputStream(new FileInputStream(filepath));
DateTimeFormatter format_day = DateTimeFormatter.ofPattern("uuuu/MM/dd");
DateTimeFormatter format_hour = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDate now_day = LocalDate.now();
LocalDateTime now_hour = LocalDateTime.now();
ArrayList<String> dates = new ArrayList<>();
ArrayList<String> expire_in_week = new ArrayList<>();
ArrayList<String> expire_tomorrow = new ArrayList<>();
ArrayList<String> expire_today = new ArrayList<>();
ArrayList<String> expired = new ArrayList<>();
while(read.available()>0) {
String name = read.readUTF();
String surname = read.readUTF();
String date = read.readUTF();
String cardcode = read.readUTF();
String cardtype = read.readUTF();
int contract_num = read.readInt();
String cert_num = read.readUTF();
String phone_num = read.readUTF();
String email = read.readUTF();
String status = read.readUTF();
String comment = read.readUTF();
dates.add(date);
for (String s:dates){
String[] data = s.split("/");
String days =data[0];
LocalDate date_days = LocalDate.parse(days.replace("-", "/"), format_day);
String hours =data[1];
LocalTime date_hours = LocalTime.parse(hours.replace("-", ":"),format_hour);
long daysbetween = ChronoUnit.DAYS.between(now_day,date_days);
long hoursbetween = ChronoUnit.HOURS.between(now_hour,date_hours);
if (daysbetween==7){
expire_in_week.add(cert_num);
}else if (daysbetween==1){
expire_tomorrow.add(cert_num);
}else if (daysbetween==0 && hoursbetween>0){
expire_today.add(cert_num);
}else if (daysbetween<0 || (daysbetween==0 && hoursbetween<0)){
expired.add(cert_num);
}else{}
}
}
System.out.println("Certificates that expires:");
System.out.println("Next week");
for (String w:expire_in_week){
System.out.print(w+"|");
}
System.out.println("Tomorrow");
for (String tm:expire_tomorrow){
System.out.print(tm+"|");
}
System.out.println("Today");
for (String td:expire_today){
System.out.print(td+"|");
}
System.out.println("Today");
for (String ex:expired){
System.out.print(ex+"|");
}
}catch(FileNotFoundException ex){ex.printStackTrace();}
catch(IOException ex){ex.printStackTrace();}
}
When i start it i got error message returned:
Exception in thread "main" java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 12:00 of type java.time.LocalTime
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:463)
at java.base/java.time.LocalDateTime.until(LocalDateTime.java:1677)
at java.base/java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
at com.company.program.expiration_date(program.java:189)
at com.company.program.main(program.java:364)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 12:00 of type java.time.LocalTime
at java.base/java.time.LocalDate.from(LocalDate.java:398)
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:458)
... 4 more

The issue is because date_hours is of type LocalDateTime and date_hours is of type LocalTime. Try using the same type for both.
LocalTime now_hour = LocalTime.now();
Side note to parse the values of LocalDate and LocalTime you can try this
String data = "2022-01-23/12-00-00";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd/HH-mm-ss");
LocalDate dateDays = LocalDate.parse(data, dateTimeFormatter);
LocalTime dateHours = LocalTime.parse(data, dateTimeFormatter);

See working example of your code here: https://github.com/RobbingDaHood/answers/blob/master/so70824574/src/Main.java
You LocalTime date_hours needs a timezone before it can be compared with LocalDateTime now_hour. So either add one to date_hours as I did in the code or remove the one from now_hour.
In my code the date_hours would get the system timezone, as the code is now. Be aware that maybe your file is not using that timezone.
Output of the example code is:
Certificates that expires:
Next week
Tomorrow
Today
Today
Cert1|
You can read more here
https://www.baeldung.com/java-8-date-time-intro
That will give you a good intro to the different date types in Java.

Related

how to change format of date from string date

I have date as a string like this
String date = "11-12-2018"
I want to change it to "2018-12-11"
with the same variable. So, I tried the code below but it doesn't give me the output I expect.
String date = "11-12-2018"
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = df.parse(date);
results in:
"0012-06-09"
I want
"2018-12-11"
You can do this 3 ways. First is using SimpleDateFormat and Date and second using DateTimeFormatter and LocalDate and third you can use Split.
1. Using Date and SimpleDateFormat
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(finalDate);
Here we have our actual date String date = "11-12-2018"; we know we want to change it to 2018-12-11
So lets parse that date into a Date object using this code
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
Okay so now we have a date object of our actual date, Now lets format it to our new date.
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
2. Using LocalDate and DateTimeFormatter
Alright here we define our date again and 2 DateTimeFormatter.
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
The first formatter is our old date format, and the second one is the new one that we are gonna convert the old date into.
Alright lets use them now!
Now we make a new LocalDate object using our oldFormatter by parsing our dateString with the oldFormatter object
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
Alright now lets format it.
String reformattedDate = dateTime.format(newFormatter);
as simple as that! Here is the full code.
String date = "11-12-2018";
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
String reformattedDate = dateTime.format(newFormatter);
System.out.println(reformattedDate);
3. Using String::Split
Okay this part is pretty simple. Lets split the date using -
String[] dates = date.split("-");
We already know the order of the date lets format it using String::format
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
Here is the full code
String date = "11-12-2018";
String[] dates = date.split("-");
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
System.out.println(reformattedDate);
Try code below that will work for your case:
First parse your input format from string,
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Then convert it to desired format,
Date dateTobeParse = null;
try {
dateTobeParse = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
if (dateTobeParse != null) {
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
String outputDate = outFormat.format(dateTobeParse);
}
This is the common function which I use for date and time conversion
public String convertDateAndTime(String date, String oldFormat, String newFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
Date currentdate;
String converted = "";
try {
currentdate = sdf.parse(date);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
converted = sdf2.format(currentdate);
} catch (ParseException e) {
e.printStackTrace();
}
return converted;
}
You just have to pass the date string and their old and new formats.
In your case call this function like this
String converteddate = convertDateAndTime("11-12-2018","dd-mm-yyyy","yyyy-MM-dd");
Try the code below that will work
1) Make method like below
public String changeDateFormat(String currentFormat, String requiredFormat, String dateString) {
String result = "";
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date = null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}//end of changeDateFormat()
1st argument of the method is your current date format in your case it will be 'dd-MM-yyyy'
2nd argument is output or requires date format in your case it will be 'yyyy-MM-dd'
3rd argument is your date that you want to change the format
2) Run the method like below
String oldFormatDate = "11-12-2018";
String myDate = changeDateFormat("dd-MM-yyyy", "yyyy-MM-dd", oldFormatDate);
Log.d(TAG, "Old formatted Date : " + oldFormatDate);
Log.d(TAG, "New Date is : " + myDate);
3) Output:
Old formatted Date : 11-12-2018
New Date is : 2018-12-11

taking input using LocalDate

everyone! I am trying to think of a way to get a date input from user using LocalDate. I am getting an error that says "Type mismatch: cannot convert from String to LocalDate." I know why this error is happening but I want to know if there's another way to get around this.
String newName = stringInput("Enter a product name: ");
String newStore = stringInput("Enter a store name: ");
LocalDate newDate = dateInput("Enter a date (like 3/3/17): ");
double newCost = doubleInput("Enter cost: ");
/* the third parameter of Purchase2 is a LocalDate which I think is the reason for my error.
* Is there any way to get around this?
*/
Purchase2 purchase = new Purchase2(newName, newStore, newDate, newCost);
purchases.add(purchase); // I'm adding these to an ArrayList
/*
* This is the method I created for newDate
* I need to take the date as String and convert it to LocalDate
*/
public static String dateInput(String userInput) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate date = LocalDate.parse(userInput, dateFormat);
System.out.println(date);
return userInput;
}
I am really new to Java so any help will be appreciated! Thank you!
Change your return of dateInput to LocalDate
public static LocalDate dateInput(String userInput) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate date = LocalDate.parse(userInput, dateFormat);
System.out.println(date);
return date ;
}
And modify :
LocalDate newDate = dateInput(stringInput("Enter a date (like 3/3/17): "));
Beside that you need care about yyyy formatter

How do I convert "HH:MM" format string to Timestamp in Java?

I have a string 09:28. and I want to convert this string to Timestamp object.
Below is my coding:
Object d = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant.DAT_STOPDATE);
Date stopDate1 = (Date)d;
SimpleDateFormat printFormat = new SimpleDateFormat("hh:mm");
String timeString = printFormat.format(stopDate1);
Now I want above String as Timestamp (only HH:MM). How to do that?
Please Use parse method to get Date Object and then construct Timestamp object.
try {
Timestamp timestamp = new Timestamp(printFormat.parse(timeString).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
You can convert date object to Timestamp directly by
Timestamp timestamp = new Timestamp(stopDate1.getTime());
You can use LocalTime to store times (from a string and vice-versa) as shown below:
Option(1): With Java8
You can use Java8's LocalTime API for this, you can look here
String timeString = printFormat.format(stopDate1);
//Get your localTime object from timeString
LocalTime localTime = LocalTime.parse(timeString);
static LocalTime parse(CharSequence text) Obtains an instance of
LocalTime from a text string such as 10:15.
Option(2): Without Java8
You need to use jodatime library API, you can look here
if you are looking for the timestamp of today's hh:mm then try this
static String todaysFtoTimestamp(String f){
long todaystimestamp = ((System.currentTimeMillis() / 86400000 ) * 86400 );
//System.out.println("today: " + todaystimestamp);
long todaysftimestamp = Integer.parseInt(fToTimestamp(f)) + todaystimestamp;
//System.out.println("todayF: " + todaysftimestamp);
return todaysftimestamp+"";
}
static String fToTimestamp(String f){
String[] fArray = f.split(":");
String r = "null hehe";
int hours = Integer.parseInt(fArray[0]);
int minutes = Integer.parseInt(fArray[1]);
r = String.valueOf((minutes + (hours * 60))*60);
return r ;
}

Using calendars or Joda-Time in java

I have a document that starts on date X and end on date Y and and goes up by one day. My task is to go through this document and find out how many days are missing from the document.
Example:
19990904 56.00
19990905 57.00
19990907 60.00
Need to print out that 19900906 is missing.
I have done some research and read about java calendar, Date, and Joda-Time, yet was unable to understand what any of them are. Can some one please explain what these functions I just mentioned do, and then make a suggestion on how to use one to accomplish my goal?
I already have this code:
String name = getFileName();
BufferedReader reader = new BufferedReader(new FileReader(name));
String line;
while ((line = reader.readLine()) != null)
{ //while
String delims = "[ ]+";
String [] holder = line.split(delims);
// System.out.println("*");
int date = Integer.parseInt(holder[0]);
//System.out.println(holder[0]);
double price = Double.parseDouble(holder[1]);
With JodaTime. (If you are only concerned with date, you should NOT use datetimes, or mess with hours,minutes, dst issues.)
final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMdd");
LocalDate date=null;
while( (line = getNextLine())!=null) {
String dateAsString = line.split(delims)[0];
LocalDate founddate = dtf.parseLocalDate(dateAsString);
if(date==null) { date= founddate; continue;} // first
if(founddate.before(date)) throw new RuntimeException("date not sorted?");
if(founddate.equals(date)) continue; // dup dates are ok?
date = date.plusDays(1);
while(date.before(foundate)){
System.out.println("Date not found: " +date);
date = date.plusDays(1);
}
}
If you only need to count missing days:
LocalDate date=null;
int cont=0;
while( (line = getNextLine())!=null) {
String dateAsString = line.split(delims)[0];
LocalDate founddate = dtf.parseLocalDate(dateAsString);
if(date==null) { date= founddate; continue;} // first
if(founddate.before(date)) throw new RuntimeException("date not sorted?");
if(founddate.equals(date)) continue; // dup dates are ok?
cont += Days.daysBetween(date, founddate)-1;
date = founddate;
}
LocalDate x = new LocalDate(dateX);
LocalDate y = new LocalDate(dateY);
int i = Days.daysBetween(x, y).getDays();
missingdays = originalSizeofList - i;
This is joda-time, its much easier than vanilla java.

Date time object from webservice showing on Android textview with pattern?

Hi I have web service that return a date object like this as a return of the Json
"/Date(922312800000+0200)/"
However i need to show it on the textview in this pattern
"19.12.2011 16:15"
how can I convert that return to this pattern ?
Edit : Here is my code still giving java.lang.IllegalArgumentException
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateText = date.format(tempEntry.getCreatedDate());
Edit : Here is the code that work for me
String dateText = tempEntry.getCreatedDate();
String dateString = dateText.replace("/Date(", "").replace(")/", "");
String[] dateParts = dateString.split("[+-]");
Date dateFormat = new Date(Long.parseLong(dateParts[0]))
It appears to me that your Date is given in milliseconds from 1970, so, something like that:
// remove the unneeded information
String date = date.replace("/Date(", "").replace(")/");
String[] dateParts = date.split("[+-]")
//get the date represented by the given millis
Calendar c = Calendar.getInstance();
c.setTime(Long.parseLong(dateParts[0]);
// proceed with formatting to the desired date format.
You need to use: DateFormat.
Simple example:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
textView.setText("Today : " + today);

Categories