get week number from string date with month name - java

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).

Related

How to get a month as an integer from the given date and print as month name format ("MMM")

I am new to Java and couldnt retrieve the month while using the below code instead month value is set to 0. Please advise the mistakes that i have done here.
*
for(int i=0;i<this.input.size();i++)
{
SimpleDateFormat sf = new SimpleDateFormat("dd/mm/yyyy");
Date purchasedate;
try {
String details = input.get(i);
String[] detailsarr = details.split(",");
purchasedate = sf.parse(detailsarr[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(purchasedate);
int month = cal.get(Calendar.MONTH);
*
After getting the above month as an integer, Could you please advise if there is anyway to print the above month value as "MMM" format?
tl;dr
LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.
"23/01/2018" , // Tip: Use standard ISO 8601 formats rather than this localized format for data-exchange of date-time values.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
) // Return a `LocalDate` object.
.getMonth() // Return a `Month` enum object representing the month of this date.
.getDisplayName( // Automatically localize, generating text of the name of this month.
TextStyle.SHORT , // Specify (a) how long or abbreviated, and (b) specify whether used in stand-alone or combo context linguistically (irrelevant in English).
Locale.US // Specify the human language and cultural norms to use in translation.
) // Returns a `String`.
See this code run live at IdeOne.com.
Jan
java.time
The modern approach uses the java.time classes that supplanted the terrible Date/Calendar/SimpleDateFormat classes.
ISO 8601
Tip: When exchanging date-time values as text, use the ISO 8601 standard formats rather than using text meant for presentation to humans. For a date-only value, that would be YYYY-MM-DD such as 2018-01-23.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( "23/01/2018" , f ) ;
Month enum
Retrieve the month as a Month enum object.
Month m = ld.getMonth() ;
Localize
Ask that Month enum to generate a String with text of the name of the month. The getDisplayName method can automatically localize for you. To localize, specify:
TextStyle to determine how long or abbreviated should the string be. Note that in some languages you may need to choose stand-alone style depending on context in which you intend to use the result.
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.
Code:
String output = m.getDisplayName( TextStyle.SHORT , Locale.US ) ;
Use enum, not integer
Notice that we had no use of an integer number to represent the month. Using an enum object instead makes our code more self-documenting, ensures valid values, and provides type-safety.
So I strongly recommend passing around Month objects rather than mere int integer numbers. But if you insist, call Month.getMonthValue() to get a number. The numbering is sane, 1-12 for January-December, unlike the legacy classes.
int monthNumber = ld.getMonthValue() ;
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, Java SE 11, and later - 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
Most 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.
java.time
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dateStringFromInput = "29/08/2018";
LocalDate purchasedate = LocalDate.parse(dateStringFromInput, dateFormatter);
int monthNumber = purchasedate.getMonthValue();
System.out.println("Month number is " + monthNumber);
Running the above snippet gives this output:
Month number is 8
Note that contrary to Calendar LocalDate numbers the months the same way humans do, August is month 8. However to get the month formatted into a standard three letter abbreviation we don’t need the number first:
Locale irish = Locale.forLanguageTag("ga");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM", irish);
String formattedMonth = purchasedate.format(monthFormatter);
System.out.println("Formatted month: " + formattedMonth);
Formatted month: Lún
Please supply your desired locale where I put Irish/Gaelic. Java knows the month abbreviations in a vast number of languages.
What went wrong in your code?
Apart from using the long outdated date and time classes, SimpleDateFormat, Date and Calendar, format pattern letters are case sensitive (this is true with the modern DateTimeFormatter too). To parse or format a month you need to use uppercase M (which you did correctly in your title). Lowercase m is for minute of the hour. SimpleDateFormat is troublesome here (as all too often): rather than telling you something is wrong through an exception it just tacitly defaults the month to January. Which Calendar in turn returns to you as month 0 because it unnaturally numbers the months from 0 through 11.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Question: Why is January month 0 in Java Calendar?
Simple way of doing this is
Calendar cal = Calendar.getInstance();
Date d = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
System.out.println(sdf.format(d));
In your case modify snippet like below:
SimpleDateFormat sf = new SimpleDateFormat("dd/mm/yyyy");
Date purchasedate;
try {
String details = input.get(i);
String[] detailsarr = details.split(",");
purchasedate = sf.parse(detailsarr[1]);
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
String month = sdf.format(purchasedate);
}

Showing wrong date (java.util.Calendar)

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.

Java Time API Locale (week of the year)

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.

Java date pattern for SQL date (ISO 9075)

I am trying to parse an SQL date string (ISO 9075) and that uses microseconds(!) instead of milliseconds, for example
2010-11-22 08:08:08.123456
However, SimpleDateFormat refuses to recognize a pattern like "yyyy-MM-dd HH:mm:ss.SSSSSS" and "yyyy-MM-dd HH:mm:ss.SSS" does not work, either.
The code I am using looks something like this:
String dateString = "2010-11-22 08:08:08.123456";
String pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS";
try
{
format = new SimpleDateFormat(pattern);
format.setLenient(false);
position.setIndex(0);
Date date1 = format.parse(dateString, position);
System.out.println("Date 1: " + date1);
Date date2 = format.parse(dateString);
System.out.println("Date 2: " + date1);
}
catch (Exception e) // Should not happen
{
e.printStackTrace();
}
Whichever of the 2 patterns (".SSS" or ".SSSSSS") I use, date1 is printer as null, whereas date2 causes a parsing exception (java.text.ParseException: Unparseable date).
Maybe chop the remaining fraction part out of the dateString before parse the date? I have the following
String dateString = "2010-11-22 08:08:08.123456";
String fraction = dateString.substring(dateString.length() - 3);
String formatString = dateString.substring(0, dateString.length() - 3);
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
ParsePosition position = new ParsePosition(0);
try
{
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
position.setIndex(0);
Date date1 = format.parse(formatString, position);
System.out.println("Date 1: " + date1);
System.out.println("Date 1 fraction: " + fraction);
Date date2 = format.parse(formatString);
System.out.println("Date 2: " + date2);
System.out.println("Date 2 fraction: " + fraction);
}
catch (Exception e) // Should not happen
{
e.printStackTrace();
}
This allow the date to parse until millisecond precision while you still retain the fraction micro part.
Hmm. Given that Date doesn't have microsecond resolution, if you know that all the SQL date strings have the full six digits after the seconds decimal point (2010-11-22 08:08:08.000000 for example), why not just chop off the final three digits and use SimpleDateFormat on the remainder?
You may want to look at DATE4J which specifically tries to deal with database dates, to nanosecond precision.
You might want to call the DateFormat parse, because I think it will cut off the string. Try:
Date date1 = format.parse(dateString);
Plus, don't use "SSSSS". According to specs, only "SSS" is valid for dateformat.
Other than that, I agree with cutting it off or parsing in SQL.
Plus, you have setLenient to false, so it's strict. So the string, being longer is going to cause it to fail. Maybe that's why it returns null. Unsure, would have to test.
tl;dr
Insert/Update.
myPreparedStatement.setObject(
… ,
Instant.parse( "2010-11-22 08:08:08.123456".replace( " " , "T" ) + "Z" )
) ;
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
String output = ldt.toString().replace( "T" , " " ) ; // Remove the standard ISO 8601 format’s use of `T` in the middle with the SQL-style SPACE.
java.time
Java 8 brings the new java.time package, to supplant the notoriously troublesome old java.util.Date, .Calendar, and SimpleDateFormat classes. Those old legacy classes are limited to milliseconds resolution while your input string has microseconds. You cannot cram six decimal places into a data type limited to three.
The date-time values in java.time have nanosecond resolution, more than enough for your microseconds. That means up to nine decimal places for a fractional second.
With JDBC 4.2 and later, use the Instant class directly.
Parse your input String. To comply with ISO 8601 format used by default in the java.time classes, replace the SPACE in the middle with a T. Your given example must be coming from a column type TIMESTAMP WITHOUT TIME ZONE which means not a specific moment, not a point on the timeline.
String input = "2010-11-22 08:08:08.123456".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
And if this input was meant to be a moment in UTC, append a Z. Then you do have a moment, a specific point on the timeline. For use with a column type of TIMESTAMP WITH TIME ZONE.
String input = "2010-11-22 08:08:08.123456".replace( " " , "T" ) + "Z" ;
Instant instant = Instant.parse( input ) ;
Send to your database.
myPreparedStatement.setObject( … , instant ) ;
…and…
Instant instant = myResultSet.getObject( … , Instant.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.
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.
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Leaving this section intact as history.
Joda-Time
As noted above, you should avoid using the java.util.Date, .Calendar, and SimpleDateFormat classes. As of Java 8 you have the choice of using java.time or Joda-Time or both, as they each their strengths and weaknesses. Joda-Time also works in earlier versions of Java.
You can parse that string using Joda-Time.
Alternatively, if you have access to the java.sql.Timestamp that generated your string, you can simply pass the Timestamp object to the constructor of a DateTime. I suggest also passing a time zone as DateTime objects know their own assigned time zone.
DateTime dateTime = new DateTime( mySqlTimestamp, DateTimeZone.UTC );
or
DateTime dateTime = new DateTime( mySqlTimestamp, DateTimeZone.forID( "Europe/Paris" ) );
Joda-Time has a resolution of milliseconds. So either way you generate the DateTime (parsing or passing), you will loose the finer fraction of the second (ignored/truncated, not rounded).
If you have control over the SQL date which is an input to the java code, you could try and retrieve the date from SQL in a format which will work ("yyyy-MM-dd HH:mm:ss.SSS").

Get name of the month in Java

I wanna programmatically convert an integer in the range 1-12 to corresponding month name. (e.g. 1 -> January, 2 -> February) etc using Java Calendar class in one statement.
Note : I want to do it using Java Calendar class only. Don't suggest any switch-case or string array solution.
Thanks.
The Calendar class is not the best class to use when it comes obtaining the localized month name in one statement.
The following is an example of obtaining the month name of a desired month specified by a int value (where January is 1), using only the Calendar class:
// Month as a number.
int month = 1;
// Sets the Calendar instance to the desired month.
// The "-1" takes into account that Calendar counts months
// beginning from 0.
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month - 1);
// This is to avoid the problem of having a day that is greater than the maximum of the
// month you set. c.getInstance() copies the whole current dateTime from system
// including day, if you execute this on the 30th of any month and set the Month to 1
// (February) getDisplayName will get you March as it automatically jumps to the next
// Month
c.set(Calendar.DAY_OF_MONTH, 1);
// Returns a String of the month name in the current locale.
c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
The above code will return the month name in the system locale.
If another locale is required, one can specify another Locale by replacing the Locale.getDefault() with a specific locale such as Locale.US.
Use DateFormatSymbols
Proudly copied and pasted from bluebones.net:
import java.text.*;
String getMonthForInt(int m) {
String month = "invalid";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (m >= 0 && m <= 11 ) {
month = months[m];
}
return month;
}
Did you read the API? The method getDisplayName(...) looks like a good place to start. Doing it in one statement is a terrible requirement.
tl;dr
Month.of( 12 ).getDisplayName( TextStyle.FULL , Locale.US )
…or…
Month.DECEMBER.getDisplayName( TextStyle.FULL , Locale.US )
December
Using java.time
The modern way to get the localized name of a month is with the java.time.Month enum. This class is part of the java.time package than now supplants the troublesome old legacy date-time classes such as Date and Calendar.
To localize, specify:
TextStyle to determine how long or abbreviated should the string be.
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.
Example code.
Month month = Month.of( 7 );
String outputConstantName = month.toString();
String outputMonthNameEnglish = month.getDisplayName( TextStyle.FULL , Locale.US );
String outputMonthQuébec = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
month.toString(): JULY
outputMonthNameEnglish: July
outputMonthQuébec: juillet
Using the Month enum objects by name rather than month number can be handy, easier to read, and less error-prone.
String output = Month.JULY.getDisplayName( TextStyle.FULL , Locale.US ) ;
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 and 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 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.

Categories

Resources