I'm trying to format the date as per requirement. Requirement is if two date consist different years then there should be different format and if month is different then different format.
Here is code
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSX");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse("2018-01-16T00:07:00.000+05:30"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("2018-03-18T00:07:00.000+05:30"));
SimpleDateFormat simpleDateformat = new SimpleDateFormat("E DD MMMM YYYY");
if(cal.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)){
stringBuilder.append(simpleDateformat.format(cal.getTime())).append(" - ").append(simpleDateformat.format(cal2.getTime()));
System.out.println("formatis"+stringBuilder.toString());
}
if(cal.get(Calendar.MONTH) != cal2.get(Calendar.MONTH)){
SimpleDateFormat diffMonthFormat = new SimpleDateFormat("E DD MMMM");
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(diffMonthFormat.format(cal.getTime())).append(" - ").append(simpleDateformat.format(cal2.getTime()));
System.out.println("formatis"+ strBuilder.toString());
}
Problem is it's working fine for different years but when i'm comparing month then output is
Tue 16 January - Sun 77 March 2018
It's showing date as 77.
Can anyone help
Day-of-month versus Day-of-year
Formatting codes are case-sensitive.
Your use of DD uppercase in SimplDateFormat is incorrect, as it means day-of-year (1-365, or 1-366 in a Leap Year). You are getting 77 for a date in March that is the seventy-seventh day into the year, 77 of 365. Use dd lowercase instead.
Your bigger problem is using the outmoded terrible classes. Use java.time instead.
java.time
You are using troublesome obsolete classes, now supplanted by the java.time classes.
DateTimeFormatter
Define your pair of DateTimeFormatter objects for generating output. Note the use of Locale argument to specify the human language and cultural norms used in localizing. Use single d instead of dd if you do not want to force a padding zero for single-digit values.
DateTimeFormatter withoutYear = DateTimeFormatter.ofPattern( "EEE dd MMMM" , Locale.US ) ;
DateTimeFormatter withYear = DateTimeFormatter.ofPattern( "EEE dd MMMM uuuu" , Locale.US ) ;
OffsetDateTime
Parse input as a OffsetDateTime as it includes an offset-from-UTC but not a time zone.
Your input strings comply with standard ISO 8601 formatting, used by default in the java.time classes. So no need to specify formatting pattern.
OffsetDateTime odtA = OffsetDateTime.parse( "2018-01-16T00:07:00.000+05:30" ) ;
OffsetDateTime odtB = …
Year & Month
Test their year part via Year class. Ditto for Month enum.
if( Year.from( odtA ).equals( Year.from( odtB ) ) ) {
// … Use `withoutYear` formatter.
} else if( Month.from( odtA ).equals( Month.from( odtB ) ) ) { // If different year but same month.
// … Use `withYear` formatter.
} else { // Else neither year nor month is the same.
// …
}
Generate string
To generate a string, pass the formatter to the date-time’s format method.
String output = odtA.format( withoutYear ) ; // Pass `DateTimeFormatter` to be used in generating a String representing this date-time object’s value.
By the way, there is also a YearMonth class if you are ever interested in year and month together.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
This question already has answers here:
Java Date - Insert into database
(10 answers)
Java: Insert into a table datetime data
(6 answers)
Closed 5 years ago.
I have the following String I get from result. How can I intelligently convert it into mysql date time format in java?
Montag, 09. April 2018, 11:00 Uhr
Thanks in advance
tl;dr
Send an object to your database, rather than a string.
myPreparedStatement.setObject( // JDBC 4.2 and later allows direct exchange of java.time objects with a database.
… ,
DateTimeFormatter.ofPattern( // Define a formatter based on a specific pattern.
"EEEE, dd. MMMM yyyy, HH:mm 'Uhr'" , // Pattern to match our input text.
Locale.GERMANY // Locale specifies human language used to parse the name of day, name of month, etc.
).parse( "Montag, 09. April 2018, 11:00 Uhr" ) // Generate a `ZonedDateTime` object.
)
Smart objects, not dumb strings
First, read the correct Answer by gil.fernandes.
Your phrase “mysql date time format” suggests working with strings. You should not be exchanging date-time values with your database as text. We have classes for that.
Parse your input string into a LocalDateTime object as shown in that answer.
DateTimeFormatter f =
DateTimeFormatter.ofPattern(
"EEEE, dd. MMMM yyyy, HH:mm 'Uhr'" ,
Locale.GERMANY
)
;
LocalDateTime ldt =
LocalDateTime.parse(
"Montag, 09. April 2018, 11:00 Uhr" ,
f
)
;
With JDBC 4.2 or later, send that object to your database. Note that LocalDateTime should only be sent to a column of type like the SQL standard TIMESTAMP WITHOUT TIME ZONE.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval:
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You can effectively do it, but I do not know if this is a good idea.
Anyway this is what would technically work:
String s = "Montag, 09. April 2018, 11:00 Uhr";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("EEEE, dd. MMMM yyyy, HH:mm 'Uhr'", Locale.GERMANY);
// Parse with the German format
LocalDateTime dateTime = LocalDateTime.parse(s, formatter); // Using Java 8 libraries
// Format with the MySQL format (Well, actually ISO)
final DateTimeFormatter formatterMysql = DateTimeFormatter.ISO_DATE_TIME;
System.out.println(formatterMysql.format(dateTime).replace("T", " "));
This will print out:
2018-04-09 11:00:00
Which should be understood by MySQL.
Below is my input date string format:
2025-08-08T15%3A41%3A46
I have to convert above string date in the format as shown below:
Fri Aug 08 15:41:46 GMT-07:00 2025
And I got below code:
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
String decodedDate = URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8");
Date date = dateParser.parse(decodedDate);
//Decode the given date and convert to Date object
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT-07:00"));
System.out.println(sdf.format(date));
And this is what it prints out on the console. I am not sure why it prints different hour value as compared to what I have above in the desired output. It should print out 15 but it is printing 03.
Fri Aug 08 03:41:46 GMT-07:00 2025
I am not sure what is the reason why hours are getting changed because of timezone difference with GMT?
That is the same time except in the first format you are using "HH" for hour that is "Hour in day (0-23)" and second format uses "hh" that is "Hour in am/pm (1-12)".
As the other Answer correctly states, your formatting pattern used incorrect characters.
Let's look at an alternative modern approach.
ISO 8601
Your input string, once decoded to restore the COLON characters, is in standard ISO 8601 format.
URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8")
2025-08-08T15:41:46
Using java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
The java.time classes use ISO 8601 by default when parsing/generating strings.
Your input string lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( "2025-08-08T15:41:46" )
ldt.toString(): 2025-08-08T15:41:46
If you know the intended time zone, assign a ZoneId to produce a ZonedDateTime.
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) ) ;
zdt.toString(): 2025-08-08T15:41:46-04:00[America/Montreal]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Howto pass a localization to the new Java Time API?
In this simple example i try to print current week-of-the-year but the result is always wrong.
import java.text.*;
import java.time.*;
import java.time.format.*;
import java.util.*;
//wrong result
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy ww");
System.out.println(LocalDateTime.now(ZoneId.of("Europe/Berlin")).format(formatter));
//this works
System.out.println(new SimpleDateFormat("yyyy ww",Locale.GERMANY).format(new Date()));
Pass the Locale to ofPattern method of DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy ww",Locale.GERMANY);
System.out.println(LocalDateTime.now().format(formatter));
tl;dr
Use proper formatting pattern, case-sensitive: "YYYY ww".
LocalDate.now( ZoneId.of( "Europe/Berlin" ) ) // Get the current date (date-only value) as seen in the wall-clock time used by the people of a certain region (a time zone).
.format( // Generate a string representing the week and week-based-year according to a particular locale’s definition of ‘week’.
DateTimeFormatter.ofPattern( "YYYY ww" ).withLocale( Locale.GERMANY )
)
yyyy ww is invalid
The yyyy coding in java.time means calendar-year. Following that with ww for a week number of a standard ISO 8601 week-based year is misleading and nonsensical.
You should be combining week-number with week-based-year number rather than calendar-year number. The formatting code for that is uppercase YYYY. So you would want YYYY ww.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "YYYY ww" ) ;
Locale affects YYYY not yyyy
Since yyyy lowercase means calendar year, specifying a Locale has no effect. Use YYYY uppercase, as mentioned above, if you want the locale-defined week-based-year.
For more info, see the Question: Java Time's week-of-week-based-year pattern parsing with DateTimeFormatter
Locale locale = Locale.GERMANY ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "YYYY ww" ).withLocale( locale ) ;
LocalDate ld = LocalDate.now( ZoneId.of( "Europe/Berlin" ) ) ; // Or "Africa/Tunis", "Pacific/Auckland" etc. Time zone is unrelated (orthogonal) to locale.
String output = ld.format( f ) ;
Standard week
Perhaps you want the ISO 8601 standard definition of week rather than a locale-defined definition. This is where week # 1 contains the first Thursday of the calendar year, and starts on a Monday, for a total of 52 or 53 weeks per year.
ISO 8601 defines a standard format for week-based year & week. You may want to consider using the standard format rather than your custom format.
Standard format is yyyy-Www for the year-week, and yyyy-Www-d to also display the day-of-week number where 1-7 is Monday-Sunday. For example, 2012-W48-6 is 2012-12-01, a Saturday (day-of-week # 6).
The DateTimeFormatter class comes with a predefined format for this, DateTimeFormatter.ISO_WEEK_DATE.
String input = "2012-W48-6";
LocalDate ld = LocalDate.parse( input , DateTimeFormatter.ISO_WEEK_DATE );
System.out.println( ld );
2012-12-01
You can generate such a string.
String output = ld.format( DateTimeFormatter.ISO_WEEK_DATE );
2012-W48-6
If you want the entire week, without the day-of-week, just truncate the string.
String output = ld.format( DateTimeFormatter.ISO_WEEK_DATE ).substring( 0 , 8 ) ;
2012-W48
YearWeek
If you will be doing much of this work at all, I suggest adding the ThreeTen-Extra library to your project. That library offers many handy classes, one of which is YearWeek to represent the standard ISO 8601 week as a whole.
YearWeek yw = YearWeek.parse( "2012-W48" ) ;
Get the current week.
YearWeek yw = YearWeek.now( ZoneId.of( "Europe/Berlin" ) )
yw.toString(): 2012-W48
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have a string containing a date in the form
04-Jan-15
and need to get the week number of the year out of it.
for the above example week 1(or 2 depending on locale and weekdays in December. never mind that).
I have this:
String[] startDate=dates[0].split("-");
int month,day,year;
year=2000+Integer.parseInt(startDate[2]);
day=Integer.parseInt(startDate[0]);
switch (startDate[1]){
case "Jan":
{
month=1;
break;
}
........
........
case "Dec":
{
month=12;
break;
}
}
Calendar temp=new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date tempDate = sdf.parse(day+"/"+month+"/"+year);
System.out.println("DATE:"+tempDate);
temp.setTime(tempDate);
System.out.println("Calendar Month:"+temp.MONTH);
System.out.println("Calendar Week:"+temp.WEEK_OF_YEAR);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This returns
DATE:Sun Jan 04 00:00:00 EET 2015
Calendar Month:2
Calendar Week:3
I tried (earlier) this
temp.set(year, month, day);
and was still getting wrong results.
Any idea?
tl;dr
For culturally-defined weeks…
LocalDate.parse(
"04-Jan-15" ,
DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US )
).get(
WeekFields.of( Locale.FRANCE ).weekOfWeekBasedYear( )
) // Gets week number for a culturally-defined week-of-year.
For standard weeks…
LocalDate.parse(
"04-Jan-15" ,
DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US )
).get(
IsoFields.WEEK_OF_WEEK_BASED_YEAR
) // Gets standard ISO 8601 week number.
java.time
You are using troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. Much simpler now to solve your problem.
Parse your input string. Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
String input = "04-Jan-15";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US );
LocalDate ld = LocalDate.parse( input , f );
Dump to console.
System.out.println( "input: " + input + " = " + ld );
input: 04-Jan-15 = 2015-01-04
Week number
Week number is culturally defined. To access week-of-year, you must specify a Locale whose culture you want to use in defining a week.
Locale locale = Locale.FRANCE;
WeekFields fields = WeekFields.of( locale );
TemporalField field = fields.weekOfWeekBasedYear( );
int weekNumber = ld.get( WeekFields.of( Locale.FRANCE ).weekOfWeekBasedYear( ) ); // Gets week number for a culturally-defined week-of-year.
ISO 8601 defines standard week numbers where week # 1 contains the first Thursday of the year, and begins on a Monday. The java.time class offer this approach built-in in the IsoFields class.
int weekNumber = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) // Gets standard ISO 8601 week number.
ISO 8601
By the way, that input string format is not good. When exchanging date-time values as text, always use ISO 8601 standard formats. These are used by default in java.time when parsing/generating strings.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
MONTH and WEEK_OF_YEAR in class Calendar are constants, not the month and week of year of any particular Calendar object.
You use these constants with the get(...) method. The constant indicates which field you want to get. Like this:
System.out.println("Calendar Month:" + temp.get(Calendar.MONTH));
System.out.println("Calendar Week:" + temp.get(Calendar.WEEK_OF_YEAR));
Also, there's a much easier way to parse a string like 04-Jan-15 into a Date object than doing it manually:
String text = "04-Jan-15";
DateFormat df = new SimpleDateFormat("dd-MMM-yy", Locale.US);
Date date = df.parse(text);
(Why are you first parsing the string manually, then converting it into another format dd/MM/yyyy and then parsing that again? That's much more complicated than necessary).
I have created new SimpleDateFormat object which parses the given string as date object. The date format is as below:
SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");
And I am setting this date to calendar instance as below:
Date date = sampledateFormat.parse("01-08-2013");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Now I am getting the day of the day of the week from this calendar. It is giving wrong value.
System.out.println(calendar.DAY_OF_WEEK);
The output it is giving is 7 i.e. Saturday but the expected value is 5 i.e. Thursday. Whats the problem?
You should print
calendar.get(Calendar.DAY_OF_WEEK);
The Calendar class has DAY_OF_WEEK as integer constant (with value 7) which should be used in conjunction with the Calendar.get(int) method. DAY_OF_WEEK is a calendar field, and all these constant fields are used to get() different values from the calendar instance. Their value is irrelevant.
tl;dr
LocalDate.parse( // Parse the input string by specified formatting pattern to get a date-only `LocalDate` object.
"01-08-2013" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.getDayOfWeek() // Get a `DayOfWeek` enum object. This is *not* a mere String.
.getValue() // Ask the `DayOfWeek` object for its number, 1-7 for Monday-Sunday per ISO 8601 standard.
4
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as SimpleDateFormat and Date and Calendar.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
Parse the input string.
LocalDate ld = LocalDate.parse( "01-08-2013" , f ) ;
ld.toString(): 2013-08-01
Interrogate for the day-of-week. Get a DayOfWeek enum object, one of seven pre-defined objects, for Monday-Sunday.
DayOfWeek dow = ld.getDayOfWeek() ;
dow.toString(): THURSDAY
You can ask that DayOfWeek object for a localized name and for a number 1-7 for Monday-Sunday per the ISO 8601 standard.
int dowNumber = dow.getValue() ;
4
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.ITALY, etc.
jeudi
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.