I have a small program that displays the current week from todays date, like this:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);
And then a JLabel that displays the week number:
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));
So right now I'd like to have a JTextField where you can enter a date and the JLabel will update with the week number of that date. I'm really not sure how to do this as I'm quite new to Java. Do I need to save the input as a String? An integer? And what format would it have to be (yyyyMMdd etc)? If anyone could help me out I'd appreciate it!
Do I need to save the input as a String? An integer?
When using a JTextField, the input you get from the user is a String, since the date can contain characters like . or -, depending on the date format you choose. You can of course also use some more sophisticated input methods, where the input field already validates the date format, and returns separate values for day, month and year, but using JTextField is of course easier to start with.
And what format would it have to be (yyyyMMdd etc)?
This depends on your requirements. You can use the SimpleDateFormat class to parse any date format:
String input = "20130507";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
But more likely you want to use the date format specific to your locale:
import java.text.DateFormat;
DateFormat defaultFormat = DateFormat.getDateInstance();
Date date = defaultFormat.parse(input);
To give the user a hint on which format to use, you need to cast the DateFormat to a SimpleDateFormat to get the pattern string:
if (defaultFormat instanceof SimpleDateFormat) {
SimpleDateFormat sdf = (SimpleDateFormat)defaultFormat;
System.out.println("Use date format like: " + sdf.toPattern());
}
The comment by #adenoyelle above reminds me: Write unit tests for your date parsing code.
Java 1.8 provides you with some new classes in package java.time:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime / java.time.Instant by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime().
tl;dr
YearWeek.from( // Represents week of standard ISO 8601 defined week-based-year (as opposed to a calendar year).
LocalDate.parse( "2017-01-23" ) // Represents a date-only value, without time-of-day and without time zone.
) // Returns a `YearWeek` object.
.getWeek() // Or, `.getYear()`. Both methods an integer number.
4
ISO 8601 standard week
If you want the standard ISO 8601 week, rather than a localized definition of a week, use the YearWeek class found in the ThreeTen-Extra project that adds functionality to the java.time classes built into Java 8 and later.
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
First, get today's date. The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Or let the user specify a date by typing a string. Parsing string input of a date is covered in many other Questions and Answers. Simplest is to have the user use standard ISO 8601 format, YYYY-MM-DD such as 2017-01-23.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
For other formats, specify a DateTimeFormatter for parsing. Search Stack Overflow for many many examples of using that class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( "1/23/2017" , f ) ;
Get the YearWeek.
YearWeek yw = YearWeek.from( ld ) ;
To create a string, consider using the standard ISO 8601 format for year-week, yyyy-Www such as 2017-W45. Or you can extract each number.
YearWeek::getWeek – Gets the week-of-week-based-year field.
YearWeek::getYear – Gets the week-based-year field.
Other definitions of week
The above discussion assumes you go by the ISO 8601 definition of weeks and week-numbering. If instead you want an alternate definition of week and week-numbering, see the Answer by Mobolaji D. using a locale’s definition.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.
WeekFields
This method that I created works for me in Java 8 and later, using WeekFields, DateTimeFormatter, LocalDate, and TemporalField.
Don't forget to format your date properly based on your use case!
public int getWeekNum(String input) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy"); // Define formatting pattern to match your input string.
LocalDate date = LocalDate.parse(input, formatter); // Parse string into a `LocalDate` object.
WeekFields wf = WeekFields.of(Locale.getDefault()) ; // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
TemporalField weekNum = wf.weekOfWeekBasedYear(); // Represent the idea of this locale’s definition of week number as a `TemporalField`.
int week = Integer.parseInt(String.format("%02d",date.get(weekNum))); // Using that locale’s definition of week number, determine the week-number for this particular `LocalDate` value.
return week;
}
You can store the date as a String, and the user can enter it in pretty much any format you specify. You just need to use a DateFormat object to interpret the date that they enter. For example, see the top answer on Convert String to Calendar Object in Java.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
To read the date from a JTextField, you could replace that with something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));
Then you just need to read the week number from cal in the same way you showed in the question. (This is a simplified example. You'd need to handle the potential ParseException thrown by the DateFormat parse method.)
You can use that, but you have to parse the date value to proper date format using SimpleDateFormatter of java API. You can specify any format you want. After that you can do you manipulation to get the week of the year.
public static int getWeek() {
return Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
}
Works fine and return week for current realtime
this one worked for me
public void sortListItems(List<PostModel> list) {
Collections.sort(list, new Comparator<PostModel>() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
#Override
public int compare(PostModel o1, PostModel o2) {
int ret = 0;
try {
ret = dateFormat.parse(o1.getDate()).compareTo(dateFormat.parse(o2.getDate()));
return ret;
} catch (ParseException e) {
e.printStackTrace();
}
return ret;
}
});
}
Related
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);
}
I have a multicultural application, the project uses Java 7. I need to show the date, but the day in month and month only. So for example in Locale.UK today's date looks like: 24/01, but in Locale.US like: 1/24. How to achieve this in Java 7? I tried to use DateFormat.getDateInstance(dateFormat, locale), but in this case I can use just predefined date formats, for example DateFormat.SHORT, DateFormat.DEFAULT etc. there is no predefined format just with the day in month and month only. Next I tried to use SimpleDateFormat with locale, but this is not working as I wonder, it just translates some text according to the locale. Here is my sample code:
DateFormat dfuk = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
DateFormat dfus = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
System.out.println(dfuk.format(new Date())); // 24/01/17
System.out.println(dfus.format(new Date())); // 1/24/17
SimpleDateFormat sdfuk = new SimpleDateFormat("dd/MM", Locale.UK);
SimpleDateFormat sdfus = new SimpleDateFormat("dd/MM", Locale.US);
System.out.println(sdfuk.format(new Date())); // 24/01
System.out.println(sdfus.format(new Date())); // 24/01
I expected last line to print 01/24 (or 1/24). How to achieve this?
Your code was throwing the same format because both DateFormat were constructed with the same pattern and that is not correct..
SimpleDateFormat sdfuk = new SimpleDateFormat("dd/MM", Locale.UK);
SimpleDateFormat sdfus = new SimpleDateFormat("dd/MM", Locale.US);
You will need the local if you have a String that is going to be converted to date... for the parsing you are trying to do (string -> Date) only the pattern is ok...
Example
DateFormat sdfuk = new SimpleDateFormat("dd/MM");
DateFormat sdfus = new SimpleDateFormat("MM/d");
System.out.println(sdfuk.format(new Date())); // 24/01
System.out.println(sdfus.format(new Date())); // 01/24
Change your third last line to
SimpleDateFormat sdfus = new SimpleDateFormat("MM/dd", Locale.US);
Overcoming the shortcoming of what standard Java offers:
The getDateInstance() method takes an argument for style. The shortest style seems to be DateFormat.SHORT. You can argue that perhaps they should provide one that is even shorter (DateFormat.SHORTER perhaps?) c.f.
http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html#getDateInstance(int)
Before that happen, you can build an enum of pattern for the shorter style. Below is an example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
enum PatternShorter { // or PatternMonthDayOnly
MM_SLASH_DD ("MM/dd")
, DD_SLASH_MM ("dd/MM")
;
private String pattern;
public String getPattern() {
return pattern;
}
private PatternShorter(String pattern) {
this.pattern = pattern;
}
public static PatternShorter getDefault() { return DD_SLASH_MM; }
}
public class DateFormatEx {
private static Map<Locale, PatternShorter> patternShorter = new HashMap<>();
static {
patternShorter.put(Locale.UK, PatternShorter.DD_SLASH_MM);
patternShorter.put(Locale.UK, PatternShorter.MM_SLASH_DD);
// any locale not listed here will get the default pattern
}
private static String getPattern (Locale locale) {
if (patternShorter.get(locale)!=null) {
return patternShorter.get(locale).getPattern();
} else {
return PatternShorter.getDefault().getPattern();
}
}
public static void main(String[] args) {
List<Locale> listOfLocale = Arrays.asList(Locale.UK, Locale.US, Locale.FRENCH);
for (Locale locale : listOfLocale) {
SimpleDateFormat fmt
= new SimpleDateFormat(getPattern(locale), locale);
System.out.format("for locale %s the shorter date/month display is: %s%n"
, locale.toString()
, fmt.format(new Date()));
}
}
}
The output would be:
for locale en_GB the shorter date/month display is: 01/24
for locale en_US the shorter date/month display is: 24/01
for locale fr the shorter date/month display is: 24/01
tl;dr
MonthDay.from(
LocalDate.now( ZoneId.of( "America/Montreal" ) )
).format( DateTimeFormatter.ofPattern( "MM/dd" ) )
01/24
MonthDay
There's a class for that: MonthDay.
The MonthDay represents the combination of a month and day-of-month.
MonthDay md = MonthDay.of( Month.JANUARY , 24 );
Avoid legacy date-time classes.
Avoid the troublesome old date-time classes such as SimpleDateFormat, now legacy, supplanted by the java.time classes.
The MonthDay class is part of the java.time framework built into Java 8 and later. Much of java.time is back-ported to Java 6 & Java 7 (see below).
ISO 8601
md.toString(): --01-24
The toString method generates a String in standard ISO 8601 format. The MonthDay class can also parse such strings.
Current date
You want the month-day of the current date. For the current date we will use the LocalDate class. The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
Be clear that Locale has nothing to do with time zones. A Locale only applies to the format of text when generating strings, but is separate and distinct from time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Now extract a MonthDay object.
MonthDay md = MonthDay.from( today );
today.toString(): 2017-01-25
md.toString(): --01-25
Other formats
You can generate strings in other formats.
The java.time classes can automatically localize some date-time values by Locale. Unfortunately, this does not apply to MonthDay. For MonthDay you must explicitly specify the desired format in a DateTimeFormatter object when you want something other than the standard ISO 8601 format. By the way, I encourage you to stick with the standard format whenever possible, especially for exchanging data. You might even consider training your users to accept this format. The standard format is unambiguous, whereas your UK-US formats (dd/MM, MM/dd) can be entirely ambiguous such as 01/02 being either January 2nd or February 1st.
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, and such. Generally, I advise always specifying a Locale for your DateTimeFormatter rather than relying implicitly on the JVM’s current default Locale. But I do not see any way the Locale would affect the output of this particular format. So I omit the Locale in this example.
DateTimeFormatter fUS = DateTimeFormatter.ofPattern( "MM/dd" );
DateTimeFormatter fUK = DateTimeFormatter.ofPattern( "dd/MM" );
String output = md.format( fUS );
Live code
See this example code run live at IdeOne.com.
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.
I ended up modifying the localized format string provided by DateFormat.getDateInstance(DateFormat.SHORT), removing the year part from the format:
DateFormat shortDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
String shortPattern = ((SimpleDateFormat) shortDateFormat).toLocalizedPattern();
String shorterPattern = shortPattern.replaceAll("[/\\- ]*[yY]+[^a-zA-Z]*", "");
DateFormat shorterDateFormat = new SimpleDateFormat(shorterPattern);
I skimmed through all 734 locales provided by my system, and the generated date patterns look good for all of them, as far as I can tell.
Some examples comparing the original short pattern to the modified shorter one:
short shorter
en_US M/d/yy M/d
en_GB dd/MM/y dd/MM
de_DE dd.MM.yy dd.MM.
fr_FR dd/MM/y dd/MM
nl_NL dd-MM-y dd-MM
ja_JP y/MM/dd MM/dd
I have parsed a java.util.Date from a String but it is setting the local time zone as the time zone of the date object.
The time zone is not specified in the String from which Date is parsed. I want to set a specific time zone of the date object.
How can I do that?
Use DateFormat. For example,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");
Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
As ZZ Coder shows, you set the timezone on the DateFormat object, to tell it in which timezone you want to display the date and time.
tl;dr
…parsed … from a String … time zone is not specified … I want to set a specific time zone
LocalDateTime.parse( "2018-01-23T01:23:45.123456789" ) // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Assign the time zone for which you are certain this date-time was intended. Instantiates a `ZonedDateTime` object.
No Time Zone in j.u.Date
As the other correct answers stated, a java.util.Date has no time zone†. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.
Avoid j.u.Date
For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.
Instead use the java.time package bundled with Java 8.
java.time
The java.time classes can represent a moment on the timeline in three ways:
UTC (Instant)
With an offset (OffsetDateTime with ZoneOffset)
With a time zone (ZonedDateTime with ZoneId)
Instant
In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instant objects for much of your business logic.
Instant instant = Instant.now();
OffsetDateTime
Apply an offset-from-UTC to adjust into some locality’s wall-clock time.
Apply a ZoneOffset to get an OffsetDateTime.
ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );
ZonedDateTime
Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).
Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
LocalDateTime
If the input string lacked any indicator of offset or zone, parse as a LocalDateTime.
If you are certain of the intended time zone, assign a ZoneId to produce a ZonedDateTime. See code example above in tl;dr section at top.
Formatted Strings
Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.
String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Joda-Time
While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.
In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );
Call the toString method to generate a String in ISO 8601 format.
String output = dateTimeIndia.toString();
Joda-Time also offers rich capabilities for generating all kinds of other String formats.
If required, you can convert from Joda-Time DateTime to a java.util.Date.
Java.util.Date date = dateTimeIndia.toDate();
Search StackOverflow for "joda date" to find many more examples, some quite detailed.
†Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString method in generating a string representation of the date-time value; instead the JVM’s current default time zone is applied on-the-fly. So, as shorthand, we often say “j.u.Date has no time zone”. Confusing? Yes. Yet another reason to avoid these tired old classes.
You could also set the timezone at the JVM level
Date date1 = new Date();
System.out.println(date1);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"
Date date2 = new Date();
System.out.println(date2);
output:
Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013
If you must work with only standard JDK classes you can use this:
/**
* Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
* <code>toTimeZone</code>. Since java.util.Date has does not really store time zome
* information, this actually converts the date to the date that it would be in the
* other time zone.
* #param date
* #param fromTimeZone
* #param toTimeZone
* #return
*/
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);
return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}
/**
* Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
* additional offset due to the time zone being in daylight savings time as of
* the given <code>date</code>.
* #param date
* #param timeZone
* #return
*/
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
long timeZoneDSTOffset = 0;
if(timeZone.inDaylightTime(date))
{
timeZoneDSTOffset = timeZone.getDSTSavings();
}
return timeZone.getRawOffset() + timeZoneDSTOffset;
}
Credit goes to this post.
java.util.Calendar is the usual way to handle time zones using just JDK classes. Apache Commons has some further alternatives/utilities that may be helpful. Edit Spong's note reminded me that I've heard really good things about Joda-Time (though I haven't used it myself).
Convert the Date to String and do it with SimpleDateFormat.
SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
readFormat.setTimeZone(TimeZone.getTimeZone("GMT" + timezoneOffset));
String dateStr = readFormat.format(date);
SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = writeFormat.parse(dateStr);
This code was helpful in an app I'm working on:
Instant date = null;
Date sdf = null;
String formatTemplate = "EEE MMM dd yyyy HH:mm:ss";
try {
SimpleDateFormat isoFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("US/Pacific")));
sdf = isoFormat.parse(timeAtWhichToMakeAvailable);
date = sdf.toInstant();
} catch (Exception e) {
System.out.println("did not parse: " + timeAtWhichToMakeAvailable);
}
LOGGER.info("timeAtWhichToMakeAvailable: " + timeAtWhichToMakeAvailable);
LOGGER.info("sdf: " + sdf);
LOGGER.info("parsed to: " + date);
Here you be able to get date like "2020-03-11T20:16:17" and return "11/Mar/2020 - 20:16"
private String transformLocalDateTimeBrazillianUTC(String dateJson) throws ParseException {
String localDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat formatInput = new SimpleDateFormat(localDateTimeFormat);
//Here is will set the time zone
formatInput.setTimeZone(TimeZone.getTimeZone("UTC-03"));
String brazilianFormat = "dd/MMM/yyyy - HH:mm";
SimpleDateFormat formatOutput = new SimpleDateFormat(brazilianFormat);
Date date = formatInput.parse(dateJson);
return formatOutput.format(date);
}
If anyone ever needs this, if you need to convert an XMLGregorianCalendar timezone to your current timezone from UTC, then all you need to do is set the timezone to 0, then call toGregorianCalendar() - it will stay the same timezone, but the Date knows how to convert it to yours, so you can get the data from there.
XMLGregorianCalendar xmlStartTime = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(
((GregorianCalendar)GregorianCalendar.getInstance());
xmlStartTime.setTimezone(0);
GregorianCalendar startCalendar = xmlStartTime.toGregorianCalendar();
Date startDate = startCalendar.getTime();
XMLGregorianCalendar xmlStartTime = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(startCalendar);
xmlStartTime.setHour(startDate.getHours());
xmlStartTime.setDay(startDate.getDate());
xmlStartTime.setMinute(startDate.getMinutes());
xmlStartTime.setMonth(startDate.getMonth()+1);
xmlStartTime.setTimezone(-startDate.getTimezoneOffset());
xmlStartTime.setSecond(startDate.getSeconds());
xmlStartTime.setYear(startDate.getYear() + 1900);
System.out.println(xmlStartTime.toString());
Result:
2015-08-26T12:02:27.183Z
2015-08-26T14:02:27.183+02:00
This answer is probably the shortest and it uses only the Date class:
long current = new Date().getTime() + 3_600_000; //e.g. your JVM time zone +1 hour (3600000 milliseconds)
System.out.printf("%1$td.%1$tm.%1$tY %1$tH:%1$tM\n", current);//european time format
But, if you can, use more modern ways to doing the same.
package org.example;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class time {
public static void main(String[] args) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
Date date=new Date();
sdf.format(date);
System.out.println(sdf.format(date));
}
}
I'm having a String having date in it, I need hh:mm:ss to be added to the date, but when i use dateFormat it gives me ParseException. Here is the code:
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startDate = "2013-09-25";
Date frmDate;
frmDate = sdff.parse(startDate);
System.out.println("from date = " + frmDate);
I get parse exception for the abv code. But if i remove the hh:mm:ss from the Date format it works fine and the output will be from date = Wed Sep 25 00:00:00 IST 2013.
But I need output like from date = 2013-09-25 00:00:00
Please help me.
Thanks in advance.
You'll need 2 SimpleDateFormat objects for that. One to parse your current date string and the other to format that parsed date to your desired format.
// This is to parse your current date string
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2013-09-25";
Date frmDate = sdf.parse(startDate); // Handle the ParseException here
// This is to format the your current date to the desired format
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String frmDateStr = sdff.format(frmDate);
Edit:-
Date doesn't have a format as such. You can only get a String representation of it using the SDF. Here an excerpt from the docs
A thin wrapper around a millisecond value that allows JDBC to identify
this as an SQL DATE value. A milliseconds value represents the number
of milliseconds that have passed since January 1, 1970 00:00:00.000
GMT.
And regarding your problem to insert it in the DB, java Date can be as such persisted in the DB date format. You don't need to do any formatting. Only while fetching the date back from DB, you can use the to_char() method to format it.
parse() is used to convert String to Date.It requires the formats to be matched otherwise you will get exception.
format() is used convert the date into date/time string.
Accroding to your requirement you need to use above two methods.
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startDate = "2013-09-25";
Date parsedDate = parser.parse(startDate);
String formattedDate = dateFormatter.format(parsedDate);//this will give your expected output
tl;dr
LocalDate.parse( "2013-09-25" ) // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay( // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "America/Montreal" ) // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
) // Returns a `ZonedDateTime` object.
.toString() // Generate a string in standard ISO 8601 format, wisely extended from the standard by appending the name of the time zone in square brackets.
2013-09-25T00:00-04:00[America/Montreal]
To generate your string, pass a DateTimeFormatter.
LocalDate.parse( "2013-09-25" ) // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay( // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "America/Montreal" ) // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
) // Returns a `ZonedDateTime` object.
.format( // Generate a string representing the value of this `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // Formatter that omits zone/offset.
).replace( "T" , " " ) // Replace the standard’s required 'T' in the middle with your desired SPACE character.
2013-09-25 00:00:00
Details
Your formatting pattern must match your input, as pointed out by others. One formatter is needed for parsing strings, another for generating strings.
Also, you are using outmoded classes.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
You can parse a string to produce a LocalDate. The standard ISO 8601 formats are used in java.time by default. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2013-09-25" ) ;
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 2013 , 9 , 25 ) ; // Years use sane direct numbering (2013 means year 2013). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 2013 , Month.SEPTEMBER , 25 ) ;
Formats
If you want to get the first moment of the day for that date, apply a time zone. As mentioned above, a date and time-of-day require the context of a time zone or offset-from-UTC to represent a specific moment on the timeline.
Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00. Let java.time determine the first moment of the day.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atZone( z ) ;
If you want output in the format shown in your Question, you can define your own format. I caution you against omitting the time zone or offset info from the resulting string unless you are absolutely certain the user can discern its meaning from the greater context.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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.
It is because your string is yyyy-MM-dd, but the date format u defined is yyyy-MM-dd hh:mm:ss.
If you change your string startDate to yyyy-MM-dd hh:mm:ss it should work
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.parse(sdf.format(new Date()));
This will return a Date type
The issue is '2013-09-25' date cannot be parsed to 'yyyy-MM-dd hh:mm:ss' date format. First you need to parse following date into its matching pattern which is 'yyyy-MM-dd'.
Once it is parsed to its correct pattern you can provide the date pattern you prefer which is 'yyyy-MM-dd hh:mm:ss'.
Now you can format the Date and it will output the date as you preferred.
SimpleDateFormat can be used to achieve this outcome.
Try this code.
String startDate = "2013-09-25";
DateFormat existingPattern = new SimpleDateFormat("yyyy-MM-dd");
DateFormat newPattern = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = existingPattern.parse(startDate);
String formattedDate = newPattern.format(date);
System.out.println(formattedDate); //outputs: 2013-09-25 00:00:00
I have a small program that displays the current week from todays date, like this:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);
And then a JLabel that displays the week number:
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));
So right now I'd like to have a JTextField where you can enter a date and the JLabel will update with the week number of that date. I'm really not sure how to do this as I'm quite new to Java. Do I need to save the input as a String? An integer? And what format would it have to be (yyyyMMdd etc)? If anyone could help me out I'd appreciate it!
Do I need to save the input as a String? An integer?
When using a JTextField, the input you get from the user is a String, since the date can contain characters like . or -, depending on the date format you choose. You can of course also use some more sophisticated input methods, where the input field already validates the date format, and returns separate values for day, month and year, but using JTextField is of course easier to start with.
And what format would it have to be (yyyyMMdd etc)?
This depends on your requirements. You can use the SimpleDateFormat class to parse any date format:
String input = "20130507";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
But more likely you want to use the date format specific to your locale:
import java.text.DateFormat;
DateFormat defaultFormat = DateFormat.getDateInstance();
Date date = defaultFormat.parse(input);
To give the user a hint on which format to use, you need to cast the DateFormat to a SimpleDateFormat to get the pattern string:
if (defaultFormat instanceof SimpleDateFormat) {
SimpleDateFormat sdf = (SimpleDateFormat)defaultFormat;
System.out.println("Use date format like: " + sdf.toPattern());
}
The comment by #adenoyelle above reminds me: Write unit tests for your date parsing code.
Java 1.8 provides you with some new classes in package java.time:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime / java.time.Instant by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime().
tl;dr
YearWeek.from( // Represents week of standard ISO 8601 defined week-based-year (as opposed to a calendar year).
LocalDate.parse( "2017-01-23" ) // Represents a date-only value, without time-of-day and without time zone.
) // Returns a `YearWeek` object.
.getWeek() // Or, `.getYear()`. Both methods an integer number.
4
ISO 8601 standard week
If you want the standard ISO 8601 week, rather than a localized definition of a week, use the YearWeek class found in the ThreeTen-Extra project that adds functionality to the java.time classes built into Java 8 and later.
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
First, get today's date. The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Or let the user specify a date by typing a string. Parsing string input of a date is covered in many other Questions and Answers. Simplest is to have the user use standard ISO 8601 format, YYYY-MM-DD such as 2017-01-23.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
For other formats, specify a DateTimeFormatter for parsing. Search Stack Overflow for many many examples of using that class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( "1/23/2017" , f ) ;
Get the YearWeek.
YearWeek yw = YearWeek.from( ld ) ;
To create a string, consider using the standard ISO 8601 format for year-week, yyyy-Www such as 2017-W45. Or you can extract each number.
YearWeek::getWeek – Gets the week-of-week-based-year field.
YearWeek::getYear – Gets the week-based-year field.
Other definitions of week
The above discussion assumes you go by the ISO 8601 definition of weeks and week-numbering. If instead you want an alternate definition of week and week-numbering, see the Answer by Mobolaji D. using a locale’s definition.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.
WeekFields
This method that I created works for me in Java 8 and later, using WeekFields, DateTimeFormatter, LocalDate, and TemporalField.
Don't forget to format your date properly based on your use case!
public int getWeekNum(String input) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy"); // Define formatting pattern to match your input string.
LocalDate date = LocalDate.parse(input, formatter); // Parse string into a `LocalDate` object.
WeekFields wf = WeekFields.of(Locale.getDefault()) ; // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
TemporalField weekNum = wf.weekOfWeekBasedYear(); // Represent the idea of this locale’s definition of week number as a `TemporalField`.
int week = Integer.parseInt(String.format("%02d",date.get(weekNum))); // Using that locale’s definition of week number, determine the week-number for this particular `LocalDate` value.
return week;
}
You can store the date as a String, and the user can enter it in pretty much any format you specify. You just need to use a DateFormat object to interpret the date that they enter. For example, see the top answer on Convert String to Calendar Object in Java.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
To read the date from a JTextField, you could replace that with something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));
Then you just need to read the week number from cal in the same way you showed in the question. (This is a simplified example. You'd need to handle the potential ParseException thrown by the DateFormat parse method.)
You can use that, but you have to parse the date value to proper date format using SimpleDateFormatter of java API. You can specify any format you want. After that you can do you manipulation to get the week of the year.
public static int getWeek() {
return Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
}
Works fine and return week for current realtime
this one worked for me
public void sortListItems(List<PostModel> list) {
Collections.sort(list, new Comparator<PostModel>() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
#Override
public int compare(PostModel o1, PostModel o2) {
int ret = 0;
try {
ret = dateFormat.parse(o1.getDate()).compareTo(dateFormat.parse(o2.getDate()));
return ret;
} catch (ParseException e) {
e.printStackTrace();
}
return ret;
}
});
}