Need to convert file name based on date [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
We have a requirement to where the input file will be KYB_FX_SPOT_AUTO.20220327 where KYB_FX_SPOT_AUTO. would be a constant and 20220327 is dynamic part which is date in format yyyyddMM, we need to assign a variable then a name AUTO_FXUPLOAD_APR2022.CSV , where other than APR2022 , rest other part is constant.
Please help me with just a piece of code to convert 20220327 name to APR2022.Please note the month in source is march and APR in target which means month has to increment by one and accordingly the year might increase in case of December month.
Thanks.

If you are using Java 8 or any later version, you can use classes from java.time.
You can convert a date String of the pattern "uuuuMMdd" to one formatted as "MMMuuuu" like this:
public static void main(String[] args) {
// your example String date
String date = "20220327";
// prepare a parser for the pattern of your input
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuuMMdd");
// parse the String to a LocalDate using the parser
LocalDate localDate = LocalDate.parse(date, parser);
// prepare a formatter for your desired output
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMuuuu", Locale.ENGLISH);
// prepare some result message using the parser and the formatter…
String resMsg = String.format("%s ———> %s",
localDate.format(parser),
localDate.format(formatter).toUpperCase());
// … then print the message
System.out.println(resMsg);
}
The output of this is
20220327 ———> MAR2022
To create your desired result considering year changes when adding or subtracting a month, maybe use a YearMonth. Create ony by getting the year and month of the LocalDate and safely add one month to it.
Here's one option:
// extract the year month and add 1
YearMonth yearMonth = YearMonth.from(localDate).plusMonths(1);
// print the result
System.out.println("+ 1 month ==> " + yearMonth.format(formatter).toUpperCase());
Appending the above lines to the example main would add another line to the output:
+ 1 month ==> APR2022

What you are looking for is date formatting. You can use Date formats to parse the date, then output it in a different format.
The relevant classes are Date and SimpleDateFormat. For the calculation part, use Calendar.
// parse the date
String input = "20220327";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = inputFormat.parse(input);
// For the calculation part, refer to the javadoc of Calendar
// ...
// output in new format
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMyyyy")
String output = outputFormat.format(myDate);

Related

How to convert string to LocalDateTime,how to solve string format "yyyymmddhhMMss" to LocalDateTime [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
How to convert string to LocalDateTime,how to solve string format "yyyymmddhhMMss" to LocalDateTime
String dateTime = "20221120000000";
LocalDateTime localDateTime = LocalDateTime.parse(dateTime);
Exception in thread "main" java.time.format.DateTimeParseException: Text '20221120000000' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1948)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at java.time.LocalDateTime.parse(LocalDateTime.java:477)
at com.company.Main.main(Main.java:21)
This should do it:
String dateTimeString = "20221120000000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
If you dont want to use the DateTimeFormatter, your String needs to be in ISO format
Edit: it isn’t in the question, but you said elsewhere:
I want it to convert to this format("yyyy-MM-dd HH:mm:ss") …
A LocalDateTime cannot have a format (its toString method invariably produces an ISO 8601 format). So to obtain a specific format you need to convert to a String again:
DateTimeFormatter wantedFormatFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(wantedFormatFormatter);
System.out.println(formattedDateTime);
This outputs:
2022-11-20 00:00:00
(I hope you didn’t expect a LocalDateTime with the format you mentioned. In case you did see this question: Can’t rid of 'T' in LocalDateTime.)

java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2

I'm trying to parse two different dates and calculate the difference between them, but the next error appears:
java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2
Here's the code:
String thisDate= mySession.getVariableField(myVariable).toString().trim();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate theDate= LocalDate.parse(thisDate, formatter);
That’s as expected (approximately).
Your format pattern string, ddMMyyyy specifies two digits day of month, two digits month and (at least) four digits year for a total of (at least) eight (8) digits. So when you give it a string consisting of only 6 digits, parsing will necessarily fail.
If your user or another system is required to give you a date in ddMMyyyy format and they give you 103545, they are making an error. Your validation caught the error, which is a good thing. You will probably want to give them a chance to try again and give you a string like for example 10112021 (for 10 November 2021).
In case (just guessing) 103545 was meant to denote a time of day, 10:35:45 then you need to use the LocalTime class for it, and you also need to change the format pattern string to specify hours, minutes and seconds instead of year, month and date.
String thisDate = "103545";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
LocalTime theTime = LocalTime.parse(thisDate, formatter);
System.out.println(theTime);
Output from this snippet is:
10:35:45
The problem here is the date parser has to recieve a date in the format specified (in this case "ddMMyyyy")
For example, this is what you would need to input for the parser to return a valid date:
String thisDate = '25Sep2000';
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate theDate = LocalDate.parse(thisDate, formatter);
I think what you want is to convert a date in milliseconds to a date with a specific format. This is what you can do:
//Has to be made long because has to fit higher numbers
long thisDate = 103545; //Has to be a valid date in milliseconds
DateFormat formatter = new SimpleDateFormat("ddMMyyyy"); //You can find more formatting documentation online
Date theDate = new Date(thisDate);
String finalDate = formatter.format(theDate);

I want to Add Months In date like 6/5/2021 to 6/6/2021, but there is only increment in Days but not in Month and Year [duplicate]

This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 1 year ago.
I want to add 2 Months in another Date but he only add 60 Days in Date and there is no increment in Months of the Date as well as in Year.
I'm using following code for adding Date in another Date. Days adding correctly but there is no increment in Month of Date. if I add 60 Days then he add but again there is no increment in Month as well as in Year. If someone help me to resolve problem then I really thank full!!!
String dob = "06/05/2021";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dob));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 60);
c.add(Calendar.MONTH,2); // Not Working
sdf = new SimpleDateFormat("dd/mm/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
String incToDate = sdf.format(resultdate);
Toast.makeText(this, incToDate, Toast.LENGTH_SHORT).show();
Your pattern is not correct, it basically reads two digits for day of month/two digits for minute of hour/4 digits for year. I'm guessing you did not want any minutes of hour in this pattern, so change the lower-case ones to upper-case ones.
If you can use java.time, you could get the desired result like this:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// provide an example date as String
String dob = "06/05/2021";
// create a formatter that can parse a String in the given format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// parse the String to a LocalDate using the previously defined formatter
LocalDate localDob = LocalDate.parse(dob, dtf);
// print the (formatted) result just to see if parsing has worked
System.out.println("Just parsed " + localDob.format(dtf));
// add two months and print a result phrase
LocalDate localDobTwoMonthsLater = localDob.plusMonths(2);
System.out.println("Adding two months results in "
+ localDobTwoMonthsLater.format(dtf));
// for completeness, add 60 days and print the result
LocalDate localDobSixtyDaysLater = localDob.plusDays(60);
System.out.println("Adding sixty days results in "
+ localDobSixtyDaysLater.format(dtf));
}
}
This code prints
Just parsed 06/05/2021
Adding two months results in 06/07/2021
Adding sixty days results in 05/07/2021

output is not what is expected (Tue Aug 20 07:52:00 IST 2019 ) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The output should be the same as
(dd-MM-yyyy HH:mm)
but could see
"Tue Aug 20 07:52:00 IST 2019"
String[] tokens = lastupdated.split(": | \\(");
Date date1 = new SimpleDateFormat("dd-MM-yyyy HH:mm").parse(tokens[1]);
System.out.println(date1);
First of all println date1 is not a valid java syntax, you should use System.out.println()
Second thing is if you want to print the date in dd-MMM-yyyy HH:mm format then you need to use SimpleDateFormat format function
Try this out
String lastupdated = "Mubasher Last Update Time: 20-Aug-2019 07:42 (GMT)";
String[] tokens = lastupdated.split(": | \\(");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
Date date = sdf.parse(new String(tokens[1]));
System.out.println(sdf.format(date));
Output
20-Aug-2019 07:42
You should print your date with a custom format
System.out.println(new SimpleDateFormat("(dd-MM-yyyy HH:mm)").format(date1));
// First you parse the String, then you display with a custom format
Otherwise Java will use standard format during print
When you call System.out.println(date1), the toString() method of java.util.Date gets called to form the string representation of the date.
As per oracle documentation, this will print the date in a format "dow mon dd hh:mm:ss zzz yyyy"
If you want to format the date to a string in the format you need, then you should use the format method to make it in the string mode you need.
SimpleDateFormat dateFormat = ..//
String formattedString = dateFormat.format(date); //..

Adding n number of days in a given particular date [duplicate]

This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
String dt="2014-04-25";
I want to add n number of days in this date ... I have searched a lot but was not able to get any good working code....
I have tried SimpleDateFormat but it is not working so please help me with the code....
You can do it using joda time library
import org.joda.time;
String dt="2014-04-25";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime = formatter.parseDateTime(dt);
DateTime oneDayPlus = dateTime.plusDays(1);
String oneDayPlusString = oneDayPlus.toString(formatter); // This is "2014-04-26"
oneDayPlus would give you the object you need.
Again, this needs you to use an extra jar file, so use it if you can introduce adding a new library.
Remember String != Date they don't have anything in common (ok, exclude the fact that a string could represent a Date ok?)
If you want to add days to a String you could convert it to a Date and use normal APIs to add days to it.
And here we use SimpleDateFormat which is used to create from a patten string a date
String dt = "2014-04-25";
// yyyy-MM-dd
// year-month-day
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try
{
Date date = format.parse(dt);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 5);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e)
{
System.out.println("Wrong date");
}
yyyy-MM-dd is our patten which corrisponds to our string.
format.parse(dt);
wil try to create a Date object from the string we passed, if it fails it throw an ParseException. (If you want to check if it works just try to pass an invalid string)
Then we create a new Calendar instance and set the date to the date we created (which corrisponds to the the date in our string) and add five days to our date.. and here we go. Now calendar will refer to the 30-04-2014.
You can replace the
calendar.add(Calendar.DAY_OF_MONTH, 5);
with
calendar.add(Calendar.DAY_OF_MONTH, n);
If you want and it will add n days.

Categories