SimpleDateFormat returns wrong date in java - java

private String dateFormatter(String olddate) {
String newDate = "";
try {
SimpleDateFormat initDate = new SimpleDateFormat("dd-MMM-yy - HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy - HH:mm");
newDate = formatter.format(initDate.parse(olddate));
} catch (ParseException e) {
e.printStackTrace();
}
return newDate;
}
Input Date is : 29-Mar-22 - 22:00
Required Output Date is : 29/03/22 - 22:00
Instead of this I will get parse exception
When I convert current date in dd-MMM-yy - HH:mm format it returns 29-M03-22 - 11:38 Which is wrong.
So please help me to solve this issue.
Thanks in advance.

Be sure your formatting pattern is using the letter M from the US-ASCII range of Unicode, as commented by Dawood ibn Kareem.
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
LocalDateTime
.parse(
"29-Mar-22 - 22:00" ,
DateTimeFormatter.ofPattern( "dd-MMM-uu - HH:mm" ).withLocale( Locale.US )
)
.format(
DateTimeFormatter.ofPattern( "dd/MM/uu - HH:mm" )
)
See this code run live at IdeOne.com.
29/03/22 - 22:00
Tip: Use four digit years. In my experience, saving two digits of space is not worth the confusion caused by the ambiguity.
Tip: Rather than hard-code such formats, (a) use only standard ISO 8601 formats for data exchange, and (b) let java.time automatically localize when producing string values for presentation to the user.
LocalDateTime
.parse(
"29-Mar-22 - 22:00" ,
DateTimeFormatter.ofPattern( "dd-MMM-uu - HH:mm" ).withLocale( Locale.US )
)
.format(
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( new Locale( "es" , "AR ") ) // Spanish language, Argentina culture.
)
29/3/22 22:00

Related

How to compare one month-with-day to another in Java?

I want to compare two date one is to take as current date and another one is static date that is from local variable. I want to compare date and month only i have written one program can anyone confirm is it right or not ?
String str="27/09";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM");
LocalDateTime now = LocalDateTime.now();
String date1=dtf.format(now);
System.out.println("fist date Date 1\t"+date1);
SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM");
Date d1 = sdformat.parse(str);
String date2=sdformat.format(d1);
System.out.println("second date Date2 \t"+date2);
int result = date1.compareTo(date2);
if (result < 0) {
System.out.println("Date1 is before Date2");
}```
LOCALDATE>STATICVARIABLE DATE this is condition and want to compare date and month only.
tl;dr
MonthDay
.of( Month.OCTOBER , 1 )
.isAfter(
MonthDay
.parse(
"27/09" ,
DateTimeFormatter.ofPattern( "dd/MM" )
)
)
Run this code at Ideone.com.
true
java.time.MonthDay
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
For a day of month, use MonthDay class.
MonthDay md = MonthDay.of( 9 , 27 ) ;
For exchanging date-time values as text, ask the publisher of your data to use only standard ISO 8601 formats. For month-day, that format is --MM-DD.
String output = md.toString() ;
--09-27
If you must accept non-standard input, define a formatting pattern with DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
Parse your input.
String input = "27/09" ;
MonthDay sept27 = MonthDay.parse( input , f ) ;
sept27.toString(): --09-27
See this code run live at Ideone.com.
You can compare MonthDay objects by using their methods isBefore, equals, and isAfter.
If you want the current year-month, you need to a time zone. For any given moment, the date varies around the globe by time zone. So near the start/end of a month, it might be “next” month in Tokyo Japan while simultaneously “previous” month in Toledo Ohio US.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
MonthDay currentYearMonth = MonthDay.now( z ) ;

Change date format Java getting Unparseable date Error

I have a date in the following format:
lastUpdatedDate = "12/14/2021 09:15:17";
I used the following code/format to convert date into yyyy-MM-dd hh:mm:ss format:
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
But it gives me below error:
java.text.ParseException: Unparseable date: "12/14/2021 09:15:17"
output should be: 2021-12-14 09:15:17
How can I achieve this?
Change the format to
SimpleDateFormat dt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
System.out.println(lastUpdatedDateFormatted);
And it should be able to parse the date then.
As you are wanting to display or output the date in yyyy-MM-dd HH:mm:ss format, you should parse the date first then format the date to desired format.
try {
String lastUpdatedDate = "12/14/2021 09:15:17";
Date lastDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(lastUpdatedDate);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastDate));
} catch (ParseException e) {
e.printStackTrace();
}
Your formatting pattern fails to match your input string.
And you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
The modern solution uses the java.time classes.
Your input lacks an indicator of time zone or offset from UTC, so parse as a LocalDateTime object.
LocalDateTime ldt =
LocalDateTime
.parse(
"12/14/2021 09:15:17" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss" ) ;
) ;
Your desired output is nearly compliant with the ISO 8601 standard format used by default in java.time, except for that SPACE in the middle rather than T.
String output = ldt.toString().replace( "T" , " " ) ;

How to parse this specific date data?

I've a csv file with this form :
I don't arrive to parse this type of data.
I try with a simple example but it doesn't work. However, I think my SimpleDateFormat is correct.
Date date = null;
String date1 ="22 févr. 17, 17:11";
SimpleDateFormat formater = null;
formater = new SimpleDateFormat("dd MMM YY , hh:mm ");
try {
date = formater.parse(date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Avoid legacy date-time classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
Use only classes from the java.time packages. For a date with time of day but lacking the context of a time zone or offset-from-UTC, that would be LocalDateTime.
Specify a Locale to determine the human language used in translation, and the cultural norms used in deciding issues of abbreviation, punctuation, capitalization, order of parts, and so on.
String input = "1 mars 17, 20:21" ;
DateTimeFormatter f =
DateTimeFormatter
.ofPattern( "d MMM uu, HH:mm" )
.withLocale( Locale.CANADA_FRENCH ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
These formatting codes are explained in the Javadoc. Study carefully. Case-sensitive.

I need a code which should get Date from Excel as YYYY-MM-DD format using java

I need a code which should get Date from Excel as YYYY-MM-DD.
It is displaying the date as 31-Dec-2050 which was originally saved in sheet as 2050-12-31 Format.
System.out.println("<" + sheet.getRow(i).getCell(24) + ">");
should get Date from Excel as YYYY-MM-DD.
tl;dr
LocalDate.parse(
"31-Dec-2050" ,
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US )
)
.toString()
java.time
Your Question is unclear as you do not explain what library you might be using to read Excel files, nor do you explain what sheet.getRow(i).getCell(24) is doing. So I can only address how to parse a date string, and not give a potentially better, deeper answer.
If you are given the string 31-Dec-2050 you can parse that as a LocalDate in Java. The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
Define a formatting pattern to match your textual input.
Pass a Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Ex:
String input = "31-Dec-2050" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
See this code run live at IdeOne.com.
ld.toString(): 2050-12-31
Import:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Then in your class:
String cv = sheet.getRow(i).getCell(24).getStringCellValue();
DateTimeFormatter dt = DateTimeFormatter.ofPattern( "uuuu-MM-dd");
System.out.println("<" + LocalDate.parse(cv).format(dt) + ">");

convert string to instant with different time component formats [duplicate]

I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS

Categories