I'm trying to make an ArrayList with Holidays and dates (both Strings), then convert date to Calendar, get the day of week (using DAY_OF_WEEK) and/or sort by date/name, but for some reason I get the same result (Calendar) for every item on the list.
This is my code:
public static ArrayList listOfHolidays = new ArrayList();
Holidays.holidaysList.add(new Holidays("Sukkot", "09/10/2014"));
Holidays.holidaysList.add(new Holidays("Hanukkah", "17/12/2014"));
Holidays.holidaysList.add(new Holidays("Purim", "16/03/2014"));
Holidays class:
Calendar calendar = Calendar.getInstance();
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
return holidayName + " falls on "
+ DayOfWeek.values()[Calendar.DAY_OF_WEEK - 1]; // Here i get the same day each time
}
#Override
public int compareTo(Holidays another) {
if(MainActivity.sortByName == true) {
return holidayName.compareToIgnoreCase(another.holidayName);
}
return convertStringToCal() - another.convertStringToCal();
}
private int convertStringToCal() {
int year, month, day;
day = Integer.valueOf(holidayDate.substring(0, 2));
month = Integer.valueOf(holidayDate.substring(3, 5));
year = Integer.valueOf(holidayDate.substring(6, 10));
calendar = Calendar.getInstance();
calendar.set(year, month, day);
return (int) calendar.getTimeInMillis();
}
I call Collections.sort() from within a radioButton method to sort.
I see multiple reasons why it may not work.
First i don't know if you omitted part of the code of you Holidays class but you never actually set the calendar object aside from the convertStringToCal() method but i don't see if this method is also called in the constructor.
Secondly and most likely your problem:
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
return holidayName + " falls on "
// Here you are using the constant Calendar.DAY_OF_WEEK
+ DayOfWeek.values()[Calendar.DAY_OF_WEEK - 1]; // Here i get the same day each time
}
It should actually look something like this:
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
return holidayName + " falls on "
+ DayOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK)]; // Now you won't get the same day every time. :)
}
Some additional notes:
I would use Date objects to hold the dates, and use SimpleDateFormat to convert Strings to Dates and the other way around.
If you use these two your Holidays class would look something like this:
public class Holidays {
private final Calendar calendar = Calendar.getInstance();
private final String holidayName;
public Holidays(String holidayName, Date date) {
this.holidayName = holidayName;
this.calendar.setTime(date);
}
#Override
public int compareTo(Holidays another) {
// Generally you should avoid passing information statically between Activities
if(MainActivity.sortByName == true) {
return holidayName.compareToIgnoreCase(another.holidayName);
}
return getTimeInMillis() - another.getTimeInMillis();
}
public long getTimeInMillis() {
return this.calendar.getTimeInMillis();
}
#Override
public String toString() {
//DayOfWeek is just an enum of days (strings)
DayOfWeek day = DayOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK)]; // Now you won't get the same day every time. :)
return String.format("%s falls of %s", this.holidayName, day);
}
}
You can create Date objects like this:
// Create date objects with calendar.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.DAY_OF_MONTH, 27);
Date date = calendar.getTime();
The Constructors of the Date object like new Date(year, month, day) are deprecated and should not be used. Always use a Calendar instance to create date objects.
With SimpleDateFormat you can convert String and Date objects like this:
// The String pattern defines how date strings are parsed and formated
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "09/10/2014";
// Convert a String to Date
Date dateFromDateString = sdf.parse(dateString);
// Convert a Date to a String
String dateStringFromDate = sdf.format(dateFromDateString);
If you need more than just simple conversion of Date and String objects you can use DateFormat. That is pretty much the Rolls Royce of Date String conversion. It can parse and format Strings in a much more general way without actually requiring a pattern and it automatically accounts for locale and much more.
Or you could just use JodaTime :)
I think the problem is in casting to int in this part of code:
return (int) calendar.getTimeInMillis();
calendar.getTimeInMillis() returns long, and casting to int should cause a problem.
tl;dr
holidays.add(
new Holiday(
LocalDate.of( 2018 , Month.MAY , 8 ) ,
"National Coconut Cream Pie Day"
)
)
java.time
This work is so much simpler with the modern java.time classes rather than obsolete legacy Calendar class and its commonly-used subclass, GregorianCalendar.
LocalDate
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.
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( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). 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( 1986 , Month.FEBRUARY , 23 ) ;
Custom class
You misused the name Holidays twice in your code, once as the name of the list collection and once as the name of the individual "holiday" class/object. Furthermore, the first used as holding a static class variable, not likely a good design.
I will assume the second is a typo, and the second should be Holiday as the name of the class representing a particular holiday on a particular date.
Your Holiday class would look something like this.
class Holiday
{
private LocalDate localDate;
private String name;
private DayOfWeek dow;
public Holiday ( LocalDate localDateArg , String nameArg )
{
this.localDate = localDateArg;
this.name = nameArg;
}
public LocalDate getLocalDate ( )
{
return localDate;
}
public String getName ( )
{
return name;
}
// With arguments.
public String format ( Locale locale , FormatStyle style )
{
String date = this.localDate.format( DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) );
String output = date + " | " + this.name;
return output;
}
#Override
public String toString ( )
{
return "Holiday{ " +
"localDate=" + localDate +
", name='" + name + '\'' +
" }";
}
}
Next, we use that class.
List
Instantiate an empty List. You can optionally set the initial capacity of the ArrayList.
List < Holiday > holidays = new ArrayList <>( 3 );
Populate that list.
holidays.add( new Holiday( LocalDate.of( 2018 , Month.MAY , 8 ) , "National Coconut Cream Pie Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.AUGUST , 9 ) , "National Rice Pudding Day" ) );
holidays.add( new Holiday( LocalDate.of( 2018 , Month.JANUARY , 5 ) , "National Whipped Cream Day" ) );
holidays.toString():
[Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }, Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }]
Sort with Comparator
To sort, pass an implementation of Comparator. Here is the classic Java syntax.
holidays.sort( new Comparator < Holiday >()
{
#Override
public int compare ( Holiday o1 , Holiday o2 )
{
int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
return c;
}
} );
Here is that same Comparator in modern Java syntax using a lambda.
holidays.sort( ( o1 , o2 ) ->
{
int c = o1.getLocalDate().compareTo( o2.getLocalDate() );
return c;
} );
Or even shorter lambda syntax, but not necessarily better.
holidays.sort( ( o1 , o2 ) -> o1.getLocalDate().compareTo( o2.getLocalDate() ) );
Either way, the results are:
holidays.toString():
[Holiday{ localDate=2018-01-05, name='National Whipped Cream Day' }, Holiday{ localDate=2018-05-08, name='National Coconut Cream Pie Day' }, Holiday{ localDate=2018-08-09, name='National Rice Pudding Day' }]
Formatting output
For your date with day-of-week, use the format method we defined that automatically localized to the human language and cultural norms we specify with a Locale and FormatStyle.
for ( Holiday holiday : holidays )
{
System.out.println( holiday.format( Locale.CANADA_FRENCH , FormatStyle.FULL ) );
}
vendredi 5 janvier 2018 | National Whipped Cream Day
mardi 8 mai 2018 | National Coconut Cream Pie Day
jeudi 9 août 2018 | National Rice Pudding Day
Or in US English, passing Locale.US:
Friday, January 5, 2018 | National Whipped Cream Day
Tuesday, May 8, 2018 | National Coconut Cream Pie Day
Thursday, August 9, 2018 | National Rice Pudding Day
Note that you can get a DayOfWeek enum object from LocalDate. From that you can automatically localize the name of that day with the DayOfWeek::getDisplayName method.
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.
Related
I'm very new to Java. So please bear with me. I have 4 variables:
mode = prior|later|value;(can have either of these 3 values)
occurrence = 2
day = Wednesday
eta = 14:00
I'm trying to implement a method which will return a list date which is based on following criteria:
case 1 : (mode=prior,occurence=2,day=wednesday,eta=14:00)
should return dates of first 2 wednesdays of the next month from current month.
output = [Wed Aug 01 14:00:00 2018, Wed Aug 08 14:00:00 2018]
case 2 : (mode=later,occurence=2,day=wednesday,eta=14:00)
should return dates of last 2 wednesdays of the next month from current month.
output = [Wed Aug 22 14:00:00 2018, Wed Aug 29 14:00:00 2018]
case 3 : (mode=value,occurence=3,day=wednesday,eta=14:00)
should return date of 3rd wednesday of the next month from current month.
output = [Wed Aug 15 14:00:00 2018, Wed Aug 29 14:00:00 2018]
This is what I've done so far,
public static List<Date> getDates(Calendar c, String mode, int occurrence, int dayNo, String eta) {
List<Date> dates = new ArrayList<Date>();
switch(mode) {
case "value": {
String[] times = eta.split(":");
c.set(Calendar.DAY_OF_WEEK, dayNo);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, occurrence);
c.set(Calendar.MONTH, Calendar.JULY + 1);
c.set(Calendar.YEAR, 2018);
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
c.set(Calendar.MINUTE, Integer.parseInt(times[1]));
dates.add(c.getTime());
}
}
return dates;
}
Is there a better way of doing what I've done. Also can somebody please help me with implementing the cases 1 and 2 ?
Avoid legacy date-time classes
You are using terrible old date-time classes that were supplanted years ago by the java.time classes.
In particular, the Calendar class (well, actually, GregorianCalendar) is replaced by ZonedDateTime.
Use types (classes)
Use smart objects rather than dumb strings, where feasible. Using appropriate types makes your code more self-documenting, ensures valid values, provides for type-safety, and lets the compiler catch your typos.
In your case, Java already provides types for most of your data. You can make your own type for the “mode”.
The enum facility in Java is much more powerful and flexible than typically seen in other languages. See Oracle Tutorial to learn more. But the basics are simple, as seen here:
public enum Mode {
PRIOR ,
LATER ,
VALUE
}
For day-of-week, use the DayOfWeek enum, pre-defining seven objects, one for each day of the week. For example, DayOfWeek.WEDNESDAY.
For time-of-day, use LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
For the current month, use YearMonth class.
Determining the current year-month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ; // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z ) ;
If you have a LocalDate, you can determine the year-month for it.
YearMonth ym = YearMonth.from( myLocalDate ) ;
I suggest having the calling method determine the YearMonth rather than make this method jump through extra hoops. A general design approach in OOP is to separate, or disentangle, responsibilities. This method we are writing should be concerned with its own needs (a year-month value) and should not have to care about how the calling method arrives at its desired year-month whether that be from current date or current month or last month, etc.
Lastly, if your goal is to get a moment in time (a date with a time-of-day), then you must also specify a time zone. A date+time without the context of a time zone (or offset-from-UTC) has no real meaning.
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(!).
So, putting this all together, your method signature could look like this:
public static List< ZonedDateTime > getDates(
YearMonth ym ,
Mode mode ,
int occurrences ,
DayOfWeek dow ,
LocalTime lt ,
ZoneId z
) { …
Logic
The solution to your first two cases, Mode.PRIOR and Mode.LATER, is the use of the TemporalAdjuster interface. Specifically, the implementations found in TemporalAdjusters class can determine the “nth” weekday-of-month such as first Wednesday. Even more specifically:
firstInMonth( DayOfWeek dayOfWeek )
lastInMonth( DayOfWeek dayOfWeek )
The main idea here is to start with the first (or last) day-of-week in the month. Then work our way down (up) through the month, week-by-week, adding (subtracting) a week at a time. Repeat for our limit of integer occurrences.
We can do a switch on our Mode enum, as discussed here. Minor point: I would prefer to use Mode.PRIOR syntax rather than just PRIOR, for clarity. However, an obscure technicality in Java forbids that syntax in a switch. So, case PRIOR: not case Mode.PRIOR:, as shown further down in sample code.
We collect our resulting ZonedDateTime objects in a List named moments.
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
Let’s look at the logic for each of our three modes.
Mode.PRIOR
Get the first day-of-week of the month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
Work our way down through the month, adding a week at a time.
We might exceed the bounds of the month, going into the following month. So check the YearMonth to see if it is the same as when when started.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Mode.LATER
This case uses the same logic as above, except we start at the bottom of the month and work our way up. Get the last day-of-week of month, then subtract a week at a time.
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Because we are going backwards through time, our collection of moments is in reverse chronological order. So, we need to sort to present these in chronological order.
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
Mode.VALUE
The last case is the simplest: Get the nth day-of-week in the month. That is simply a one-liner.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
Do the usual, make a ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
Verify the month, as the documentation seems to be saying that exceeding the limits of the month takes us into the next month. In such a case, our logic omits the date from our list. So we will be returning moments as an empty list. This means the calling method should check for the list having elements, as it may be empty.
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
Let’s see all the code put together.
// Simulate arguments passed.
LocalTime lt = LocalTime.of( 14 , 0 );
ZoneId z = ZoneId.of( "Africa/Tunis" ); // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z );
DayOfWeek dow = DayOfWeek.WEDNESDAY;
Mode mode = Mode.PRIOR ; // Mode.PRIOR, Mode.LATER, Mode.VALUE.
int occurrences = 3; // TODO: Add code to verify this value is in range of 1-5, not zero, not >5.
// Logic
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
switch ( mode ) {
case PRIOR:
// Start with first day-of-week in month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
// Work our way down through the month, adding a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
break;
case LATER:
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
break;
case VALUE:
// Get the nth day-of-week in month.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
break;
default: // Defensive programming, testing for unexpected values.
System.out.println( "ERROR - should not be able to reach this point. Unexpected `Mode` enum value." );
break;
}
// return `moments` list from your method.
System.out.println( "moments:\n" + moments );
Note that the specified time-of-day on a particular date in our specified time zone may not be valid. For example, during a cutover in Daylight Saving Time (DST). If so, the ZonedDateTime class adjusts as needed. Be sure to read the documentation to make sure you understand and agree to its adjustment algorithm.
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.
So as I understand your question I wrote some code for example. I could not understand the "value" option. Desired output and explanation of method is not obvious for me. If you explain it I could edit the answer.
public class Main {
public static void main(String[] args) {
for (String s : findOccurence("prior", DayOfWeek.WEDNESDAY, 2, "14:00")){
System.out.println(s);
}
}
public static String[] findOccurence(String mode, DayOfWeek day, int occurrence, String eta) {
LocalDate now = LocalDate.now();
LocalDate start = LocalDate.of(now.getYear(), now.getMonth().plus(1), 1);
LocalDate finish = start.plusDays(start.lengthOfMonth());
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, finish))
.filter(d -> d.getDayOfWeek() == day)
.collect(Collectors.toList());
String[] formattedEta = eta.split(":");
if (occurrence > dates.size()) {
throw new IndexOutOfBoundsException();
}
if (mode.equalsIgnoreCase("value")) {
}
else if (mode.equalsIgnoreCase("later")) {
dates = Lists.reverse(dates);
}
//later and prior shares common logic
return dates.stream()
.limit(occurrence)
.map(d -> day.toString()
+ " "
+ start.getMonth().name()
+ " "
+ d.getDayOfMonth()
+ " "
+ LocalTime.of(Integer.valueOf(formattedEta[0]), Integer.valueOf(formattedEta[1]), 0)
+ " "
+ start.getYear())
.collect(Collectors.toList())
.toArray(new String[occurrence]);
}
}
Output is :
WEDNESDAY AUGUST 1 14:00 2018
WEDNESDAY AUGUST 8 14:00 2018
I have a date in dd/mm (15/07) format, I need to add a single day to this date, so it becomes 16/07.
How can I do this in the easiest way in java?
You can use Calendar.
String dt = "15-07-2016";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
You can do this:
public String addDay(String date) {
String[] dateSplit = date.split("/");
String day = "" + (Integer.parseInt(dateSplit[0]) + 1);
return day + "/" + dateSplit[1];
}
But this isn't really a nice solution, because this doesn't handle month or year swaps (This you can add by yourself using the % operator)
Or you use the SimpleDateFormat like here: How can I increment a date by one day in Java?
java.time
The Answer by Goel is correct but outmoded.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
MonthDay
The java.time classes include the MonthDay class to represent a month+day without year and without time zone.
String input = "15/07";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM" );
MonthDay monthDay = MonthDay.parse( input , formatter );
Cannot increment February 28
As commented by Tom, you cannot reliably increment February 28. In most years you would get March 1 but in leap years you get February 29. This is why the YearMonth class lacks any addDays method.
So you need to (a) assume/supply a year, (b) refuse to increment the one day of February 28, or (c) arbitrarily increment to March 1 from February 28 to ignore any possible 29th.
Let's look at the first option, supplying a year.
To get the current year we need the current date. To get the current date, specify a time zone. For any given moment, the date varies around the globe by zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
int year = today.getYear();
We can apply that year number to change our YearMonth into a LocalDate. From there the LocalDate::plusDays method increments to the next day. From the resulting instance of LocalDate we extract a YearMonth object.
LocalDate ld = monthYear.atYear( year );
LocalDate nextDay = ld.plusDays( 1 );
YearMonth ymNextDay = MonthDay.from( nextDay );
I am trying to get the date of Monday or Thurday in this format YYYYMMDD
For Monday it should give me this - 20130224 (as an example)
For Thursday it should give me this - 20130227 (as an example)
Now, if I am running my program after Thursday or on Thursday, it should print date for Thursday in this format YYYYMMDD which can be 20130227 (coming thursday in this week).
And If I am running my program after Monday or on Monday, then it should print date for Monday in the same format YYYYMMMDD which can be 20130224 (yesterday Monday date as an example)
How would I do this in Java?
Below is what I have tried -
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("EEE");
String text = formatter.format(cal.getTime());
System.out.println(text);
// but how do I check if it is Tuesday but less than Thursday
if(text.equalsIgnoreCase("Tue")) {
// get previous Monday date in YYYYMMDD
}
// and how do I check if it is thursday or greater than Thursday?
else if(text.equalsIgnoreCase("Thur")) {
// get previous Thursday date in YYYYMMDD
}
Update:-
In a particular week, if I am running my program on Thursday or after Thursday then it should return me date for Thursday in the same week in YYYYMMDD format, but if I am running my program on Monday or after Monday, then it should return me date for Monday in the same week in YYYYMMDD format.
For example, In this week, if I am running my program on Thursday or after Thursday, then it should return date for Thursday. But if I am running my program on Monday or Tuesday or Wednesday in this same week, then it should return me date for Monday.
Code:-
Below is my code -
public static void main(String[] args) {
try {
Calendar cal = Calendar.getInstance();
SimpleDateFormat toDateFormat = new SimpleDateFormat("yyyyMMdd");
int dow = cal.get(Calendar.DAY_OF_WEEK);
switch (dow) {
case Calendar.THURSDAY:
case Calendar.FRIDAY:
case Calendar.SATURDAY:
case Calendar.SUNDAY:
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY) {
cal.add(Calendar.DATE, -1);
}
break;
case Calendar.MONDAY:
case Calendar.TUESDAY:
case Calendar.WEDNESDAY:
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DATE, -1);
}
break;
}
System.out.println(date);
System.out.println(cal.getTime());
System.out.println(toDateFormat.format(cal.getTime()));
} catch (ParseException exp) {
exp.printStackTrace();
}
}
Start by parsing the text value to a Date value...
String dateText = "20130224";
SimpleDateFormat toDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = toDateFormat.parse(dateText);
This gives you the starting point. Next you need to use a Calendar which will allow you move backwards and forwards, automatically rolling the date internally for you (so if you roll over week, month or year boundaries)
For example...
try {
String dateText = "20130227";
SimpleDateFormat toDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = toDateFormat.parse(dateText);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dow = cal.get(Calendar.DAY_OF_WEEK);
switch (dow) {
case Calendar.THURSDAY:
case Calendar.FRIDAY:
case Calendar.SATURDAY:
case Calendar.SUNDAY:
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY) {
cal.add(Calendar.DATE, -1);
}
break;
case Calendar.MONDAY:
case Calendar.TUESDAY:
case Calendar.WEDNESDAY:
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DATE, -1);
}
break;
}
System.out.println(date);
System.out.println(cal.getTime());
} catch (ParseException exp) {
exp.printStackTrace();
}
So, based on this example, it would output...
Wed Feb 27 00:00:00 EST 2013
Mon Feb 25 00:00:00 EST 2013
For 20130224 (which is a Sunday) it will give
Sun Feb 24 00:00:00 EST 2013
Thu Feb 21 00:00:00 EST 2013
I should also add, there's probably a much easier way to do this with JodaTime, but this is what I was able to wipe up quickly. Yes, I know the case statement is little winded, but SUNDAY is equal to 0, which is a little annoying ;)
What? Moving to a new question with the same contents?
String[] weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // Sun=1, Mon=2, ... Sat=7
System.out.println("Today " + df.format(c.getTime()) + " is " + weeks[dayOfWeek-1]);
c.add(Calendar.DATE, 7); // Adding 7 days
System.out.println("Next " + weeks[dayOfWeek-1] + " is " + df.format(c.getTime()));
// Should display:
// Today 20140225 is Tuesday
// Next Tuesday is 20140304
I would use the calendar class day to get the day of the week. Calendar.DAY_OF_WEEK function returns 1 - 7 for Sunday - Saturday. This way you can do numeric comparison and not mess around with comparing the strings for the weekdays (which would be a mess if your app needs to support multiple languages).
See:
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
If I understood what you're after, then this should work
private static final java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
public static String calculateCorrectDate(
java.util.Date d) {
java.util.Calendar cal = java.util.Calendar
.getInstance();
cal.setTime(d);
int dayOfWeek = cal
.get(java.util.Calendar.DAY_OF_WEEK);
if (dayOfWeek >= java.util.Calendar.MONDAY
&& dayOfWeek < java.util.Calendar.THURSDAY) {
cal.set(java.util.Calendar.DAY_OF_WEEK,
java.util.Calendar.MONDAY);
} else {
cal.set(java.util.Calendar.DAY_OF_WEEK,
java.util.Calendar.THURSDAY);
}
return sdf.format(cal.getTime());
}
public static void main(String[] args) {
java.util.List<java.util.Date> dates = new java.util.ArrayList<java.util.Date>();
java.util.Calendar cal = java.util.Calendar
.getInstance();
String today = sdf.format(cal.getTime());
cal.add(java.util.Calendar.DAY_OF_WEEK, -10);
for (int i = 0; i < 20; i++) {
dates.add(cal.getTime());
cal.add(java.util.Calendar.DAY_OF_WEEK, 1);
}
for (java.util.Date d : dates) {
if (sdf.format(d).equals(today)) {
System.out.println("TODAY!");
}
System.out.println(calculateCorrectDate(d));
}
}
Which gives the output
20140213
20140220
20140217
20140217
20140217
20140220
20140220
20140220
20140227
20140224
TODAY!
20140224
20140224
20140227
20140227
20140227
20140306
20140303
20140303
20140303
20140306
or with a few import(s),
// Import Static
// This simplifies accessing the Calendar fields. Use sparingly.
import static java.util.Calendar.DAY_OF_WEEK;
import static java.util.Calendar.MONDAY;
import static java.util.Calendar.THURSDAY;
// The other imports.
import java.util.Calendar;
import java.util.Date;
Then you can use,
public static String calculateCorrectDate(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
// By using import static this remains concise and correct.
int dayOfWeek = cal.get(DAY_OF_WEEK);
if (dayOfWeek >= MONDAY && dayOfWeek < THURSDAY) {
cal.set(DAY_OF_WEEK, MONDAY);
} else {
cal.set(DAY_OF_WEEK, THURSDAY);
}
return sdf.format(cal.getTime());
}
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This Answer is left intact as history. See my modern Answer instead.
Yes, Joda-Time is the solution.
Or the new java.time package in Java 8. Inspired by Joda-Time but re-architected. Defined by JSR 310.
Next Monday/Thursday
Search StackOverflow for getting first or last day of week. That will show you how to get next monday or thursday. I won't cover that part of your question here.
Testing Day Of Week
Testing for the day of week by the English word is prone to break if you ever happen to run where English is not the default locale. Instead, get day of week by number. Joda-Time uses ISO 8601 as its defaults, so Monday = 1, Sunday = 7. Constants are provided, so you needn't memorize the numbers.
Date Without Time
If you truly don't care about time-of-day, only date, then we can use LocalDate rather than DateTime.
Example Code
Some code to get you started, using Joda-Time 2.3.
String input = "20130224";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "yyyyMMdd" );
LocalDate localDate = formatterInput.parseLocalDate( input );
int dayOfWeek = localDate.getDayOfWeek();
boolean isMonday = ( localDate.getDayOfWeek() == DateTimeConstants.MONDAY );
boolean isThursday = ( localDate.getDayOfWeek() == DateTimeConstants.THURSDAY );
Dump to console…
System.out.println( "localDate: " + localDate );
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "isMonday: " + isMonday );
System.out.println( "isThursday: " + isThursday );
When run…
localDate: 2013-02-24
dayOfWeek: 7
isMonday: false
isThursday: false
tl;dr
If:
EnumSet.range( DayOfWeek.MONDAY , DayOfWeek.WEDNESDAY ) // Monday, Tuesday, & Wednesday.
contains( LocalDate.now().getDayOfWeek() ) // If today’s date is a day-of-week that happens to be a member of that `Set`.
…then, apply:
TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) // Adjust into an earlier `LocalDate` that is a Monday, unless today already is Monday.
…else apply:
TemporalAdjusters.previousOrSame( DayOfWeek.THURSDAY ) // Otherwise move to a Thursday.
java.time
The modern approach uses the java.time classes. So much easier to solve this Question.
LocalDate
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.
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.
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( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). 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( 1986 , Month.FEBRUARY , 23 ) ;
DayOfWeek enum
The DayOfWeek enum defines a set of seven objects, one for each day of the week.
An EnumSet is a highly-optimized implementation of Set for collecting enum objects. So we can make a pair of EnumSet objects to hold a collection of DayOfWeek objects to define your two conditions: (Monday & Tuesday) versus (Thursday…Sunday).
Despite mysteriously failing to implement SortedSet, an EnumSet is indeed sorted in the natural order (declared order) of the enum. For DayOfWeek that would be Monday-Sunday, numbered 1-7 though you may never need those numbers.
Set < DayOfWeek > mondayDays = EnumSet.range( DayOfWeek.MONDAY , DayOfWeek.WEDNESDAY ); // Monday, Tuesday, & Wednesday.
Set < DayOfWeek > thursdayDays = EnumSet.range( DayOfWeek.THURSDAY , DayOfWeek.SUNDAY ); // Thursday, Friday, Saturday, Sunday.
Get the day-of-week for our source date. Prepare to match that against our enum sets.
LocalDate ld = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ; // Get today’s current date in a particular time zone.
DayOfWeek dow = ld.getDayOfWeek();
LocalDate target = LocalDate.EPOCH; // Or null. The `LocalDate.EPOCH` is first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
See which Set has the day-of-week of our date. From there, adjust into a previous or same date for the desired day-of-week (Monday or Thursday).
if ( mondayDays.contains( dow ) )
{
target = ld.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );
} else if ( thursdayDays.contains( dow ) )
{
target = ld.with( TemporalAdjusters.previousOrSame( DayOfWeek.THURSDAY ) );
} else
{
System.out.println( "ERROR - Unexpectedly reached IF-ELSE. " );
}
Generate string in your desired format. Your chosen format happens to be the “basic” version of standard ISO 8601 format where the use of delimiters is minimized.
String output = target.format( DateTimeFormatter.BASIC_ISO_DATE ) ; // YYYY-MM-DD
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.
hi i want to make a program in java where days,weekNo is parameter ..Like First Friday of the month or second Monday of the month ..and it returns the date
Here's a utility method that does that, using DateUtils from Apache Commons / Lang:
/**
* Get the n-th x-day of the month in which the specified date lies.
* #param input the specified date
* #param weeks 1-based offset (e.g. 1 means 1st week)
* #param targetWeekDay (the weekday we're looking for, e.g. Calendar.MONDAY
* #return the target date
*/
public static Date getNthXdayInMonth(final Date input,
final int weeks,
final int targetWeekDay){
// strip all date fields below month
final Date startOfMonth = DateUtils.truncate(input, Calendar.MONTH);
final Calendar cal = Calendar.getInstance();
cal.setTime(startOfMonth);
final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
final int modifier = (weeks - 1) * 7 + (targetWeekDay - weekDay);
return modifier > 0
? DateUtils.addDays(startOfMonth, modifier)
: startOfMonth;
}
Test code:
// Get this month's third thursday
System.out.println(getNthXdayInMonth(new Date(), 3, Calendar.THURSDAY));
// Get next month's second wednesday:
System.out.println(getNthXdayInMonth(DateUtils.addMonths(new Date(), 1),
2,
Calendar.WEDNESDAY)
);
Output:
Thu Nov 18 00:00:00 CET 2010
Wed Dec 08 00:00:00 CET 2010
And here's a JodaTime version of the same code (I've never used JodaTime before, so there's probably a simpler way to do it):
/**
* Get the n-th x-day of the month in which the specified date lies.
*
* #param input
* the specified date
* #param weeks
* 1-based offset (e.g. 1 means 1st week)
* #param targetWeekDay
* (the weekday we're looking for, e.g. DateTimeConstants.MONDAY
* #return the target date
*/
public static DateTime getNthXdayInMonthUsingJodaTime(final DateTime input,
final int weeks,
final int targetWeekDay){
final DateTime startOfMonth =
input.withDayOfMonth(1).withMillisOfDay(0);
final int weekDay = startOfMonth.getDayOfWeek();
final int modifier = (weeks - 1) * 7 + (targetWeekDay - weekDay);
return modifier > 0 ? startOfMonth.plusDays(modifier) : startOfMonth;
}
Test Code:
// Get this month's third thursday
System.out.println(getNthXdayInMonthUsingJodaTime(new DateTime(),
3,
DateTimeConstants.THURSDAY));
// Get next month's second wednesday:
System.out.println(getNthXdayInMonthUsingJodaTime(new DateTime().plusMonths(1),
2,
DateTimeConstants.WEDNESDAY));
Output:
2010-11-18T00:00:00.000+01:00
2010-12-08T00:00:00.000+01:00
public static Date getDate(int day, int weekNo, int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE,1);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
for (int i = 0; i < 31; i++) {
if (cal.get(Calendar.WEEK_OF_MONTH) == weekNo
&& cal.get(Calendar.DAY_OF_WEEK) == day) {
return cal.getTime();
}
cal.add(Calendar.DATE,1);
}
return null;
}
Calling code
System.out.println(""+getDate(Calendar.MONDAY, 2, Calendar.DECEMBER,2010));
Output
Mon Dec 06 15:09:00 IST 2010
Resource
Also look at Joda Time it is better
tl;dr
LocalDate firstFridayThisMonth =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) )
Using java.time
The other Answers are now outdated. The troublesome old date-time classes (Date, Calendar, etc.) are now legacy, supplanted by the java.time classes.
LocalDate
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 );
TemporalAdjuster
The TemporalAdjuster interface provides for manipulating date-time values. The java.time classes use immutable objects, so the result is always a fresh new object with values based on the original.
The TemporalAdjusters class (note plural name) provides several handy implementations. Amongst those are ones to get ordinal day-of-week within the month: firstInMonth(), lastInMonth(), and dayOfWeekInMonth(). All of these take an argument of a DayOfWeek enum object.
LocalDate firstFridayOfThisMonth =
today.with(
TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY )
)
;
…and…
LocalDate secondMondayOfThisMonth =
today.with(
TemporalAdjusters.dayOfWeekInMonth( 2 , DayOfWeek.MONDAY )
)
;
…and…
LocalDate thirdWednesdayOfNextMonth =
today.plusMonths( 1 )
.with(
TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.WEDNESDAY )
)
;
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.
Calendar cal = Calendar.getInstance();
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
this should do what you want.
edit:
with some more calculate steps, you could have result :) (sorry for confuse your title)
How can I get the year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java? I would like to have them as Strings.
You can use the getters of java.time.LocalDateTime for that.
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, when you're not on Java 8 yet, make use of java.util.Calendar.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Either way, this prints as of now:
2010-04-16 15:15:17.816
To convert an int to String, make use of String#valueOf().
If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter (tutorial here),
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
or when you're not on Java 8 yet, use java.text.SimpleDateFormat:
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Either way, this yields:
2010-04-16T15:15:17.816
Fri, 16 Apr 2010 15:15:17 GMT
20100416151517
See also:
Java string to date conversion
Switch to joda-time and you can do this in three lines
DateTime jodaTime = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));
You also have direct access to the individual fields of the date without using a Calendar.
System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());
Output is as follows:
jodaTime = 2010-04-16 18:09:26.060
year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60
According to http://www.joda.org/joda-time/
Joda-Time is the de facto standard date and time library for Java.
From Java SE 8 onwards, users are asked to migrate to java.time
(JSR-310).
// Java 8
System.out.println(LocalDateTime.now().getYear()); // 2015
System.out.println(LocalDateTime.now().getMonth()); // SEPTEMBER
System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 36
System.out.println(LocalDateTime.now().getSecond()); // 51
System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100
// Calendar
System.out.println(Calendar.getInstance().get(Calendar.YEAR)); // 2015
System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1); // 9
System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 35
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND)); // 481
// Joda Time
System.out.println(new DateTime().getYear()); // 2015
System.out.println(new DateTime().getMonthOfYear()); // 9
System.out.println(new DateTime().getDayOfMonth()); // 29
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 19
System.out.println(new DateTime().getSecondOfMinute()); // 16
System.out.println(new DateTime().getMillisOfSecond()); // 174
// Formatted
// 2015-09-28 17:50:25.756
System.out.println(new Timestamp(System.currentTimeMillis()));
// 2015-09-28T17:50:25.772
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));
// Java 8
// 2015-09-28T17:50:25.810
System.out.println(LocalDateTime.now());
// joda time
// 2015-09-28 17:50:25.839
System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));
tl;dr
ZonedDateTime.now( // Capture current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "America/Montreal" ) // Specify desired/expected time zone. Or pass `ZoneId.systemDefault` for the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMinute() // Extract the minute of the hour of the time-of-day from the `ZonedDateTime` object.
42
ZonedDateTime
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime.
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 during runtime(!), 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" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Call any of the many getters to pull out pieces of the date-time.
int year = zdt.getYear() ;
int monthNumber = zdt.getMonthValue() ;
String monthName = zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.JAPAN ) ; // Locale determines human language and cultural norms used in localizing. Note that `Locale` has *nothing* to do with time zone.
int dayOfMonth = zdt.getDayOfMonth() ;
String dayOfWeek = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
int hour = zdt.getHour() ; // Extract the hour from the time-of-day.
int minute = zdt.getMinute() ;
int second = zdt.getSecond() ;
int nano = zdt.getNano() ;
The java.time classes resolve to nanoseconds. Your Question asked for the fraction of a second in milliseconds. Obviously, you can divide by a million to truncate nanoseconds to milliseconds, at the cost of possible data loss. Or use the TimeUnit enum for such conversion.
long millis = TimeUnit.NANOSECONDS.toMillis( zdt.getNano() ) ;
DateTimeFormatter
To produce a String to combine pieces of text, use DateTimeFormatter class. Search Stack Overflow for more info on this.
Instant
Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant.
Instant instant = zdt.toInstant() ;
And go back again.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDateTime
A couple of other Answers use the LocalDateTime class. That class in not appropriate to the purpose of tracking actual moments, specific moments on the timeline, as it intentionally lacks any concept of time zone or offset-from-UTC.
So what is LocalDateTime good for? Use LocalDateTime when you intend to apply a date & time to any locality or all localities, rather than one specific locality.
For example, Christmas this year starts at the LocalDateTime.parse( "2018-12-25T00:00:00" ). That value has no meaning until you apply a time zone (a ZoneId) to get a ZonedDateTime. Christmas happens first in Kiribati, then later in New Zealand and far east Asia. Hours later Christmas starts in India. More hour later in Africa & Europe. And still not Xmas in the Americas until several hours later. Christmas starting in any one place should be represented with ZonedDateTime. Christmas everywhere is represented with a LocalDateTime.
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….
With Java 8 and later, use the java.time package.
ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();
ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.
Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it
in production code. Joda is better.
import java.sql.Timestamp;
public class DateTest {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(new Timestamp(System.currentTimeMillis()));
}
}
in java 7 Calendar one line
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(Calendar.getInstance().getTime())
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm
Look at the API documentation for the java.util.Calendar class and its derivatives (you may be specifically interested in the GregorianCalendar class).
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
now.MONTH
now.HOUR
etc.