Retrieve current week's Monday's date - java

We have a utility that will run any day between Monday - Friday. It will update some number of files inside a Content Management Tool. The last modified date associated with that file should be, that week's monday's date. I wrote the following program to retrieve current week's monday's date. But I am still not sure whether this would work for all scenarios. Has anyone got a better solution ?
Calendar c = Calendar.getInstance();
c.setTime(new Date());
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
int mondayNo = c.get(Calendar.DAY_OF_MONTH)-c.get(Calendar.DAY_OF_WEEK)+2;
c.set(Calendar.DAY_OF_MONTH,mondayNo);
System.out.println("Date "+c.getTime());

I would strongly recommend using Joda Time instead (for all your date/time work, not just this):
// TODO: Consider time zones, calendars etc
LocalDate now = new LocalDate();
LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(monday);
Note that as you've used Monday here, which is the first day of the week in Joda Time, this will always return an earlier day (or the same day). If you chosen Wednesday (for example), then it would advance to Wednesday from Monday or Tuesday. You can always add or subtract a week if you need "the next Wednesday" or "the previous Wednesday".
EDIT: If you really want to use java.util.Date/Calendar, you can use:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
You can use Calendar.setFirstDayOfWeek to indicate whether a week is Monday-Sunday or Sunday-Saturday; I believe setting the day of the week will stay within the current week - but test it.

tl;dr
LocalDate previousMonday =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time framework built into Java 8 and later. See Oracle Tutorial. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. With modern Android tooling and its "API desugaring", you need not add any library.
The java.time.LocalDate class represents a date-only value without time-of-day and without time zone.
Determining today's date requires a time zone, a ZoneId.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
The TemporalAdjuster interface (see Tutorial) is a powerful but simple way to manipulate date-time values. The TemporalAdjusters class (note the plural) implements some very useful adjustments. Here we use previous( DayOfWeek).
The handy DayOfWeek enum makes it easy to specify a day-of-week.
LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );
If today is Monday, and you want to use today rather than a week ago, call previousOrSame.
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.

The following will work, including wrapping months:
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
int today = c.get(Calendar.DAY_OF_WEEK);
c.add(Calendar.DAY_OF_WEEK, -today+Calendar.MONDAY);
System.out.println("Date "+c.getTime());
If, however, you edit your application on a Sunday (eg. Sunday 12 Feb), the date will be for the following Monday. Based on your requirements (the app will only run Monday thru Friday), this should not pose a problem.

As Jon suggested, the calendar.set method works...
I've tested it both in the case of a monday in same month and in another month using following snippet :
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
//go to the 1st week of february, in which monday was in january
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Date " + c.getTime());
//test that setting day_of_week to monday gives a date in january
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
//same for tuesday
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println("Date " + c.getTime());
The results:
Date Mon Feb 13 10:29:41 CET 2012
Date Wed Feb 01 10:29:41 CET 2012
Date Mon Jan 30 10:29:41 CET 2012
Date Tue Jan 31 10:29:41 CET 2012

What about using Joda Time library... Take look at this answer...

in case you don't want to use Joda Time you can do like this to find the weeks -> (works on Android)
public static ArrayList<String> getWeeks(int month) {
ArrayList<String> arrayListValues = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
int day = calendar.get(Calendar.DAY_OF_WEEK);
while (day != 1) {
calendar.add(Calendar.DATE, 1);
day = calendar.get(Calendar.DAY_OF_WEEK);
}
calendar.add(Calendar.DATE, -14);
String y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
String y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);
y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);
for (int i = 0; i < 10; i++) {
y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);
}
return arrayListValues;
}

For version Android 6.0 or grater use:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int day = 1, month = 7, year = 2018;
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(year, month, day);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //change de day to monday
String dateMonday= sdf.format(c.getTime());
For version Android 5.1 or less it does not work appropriately, I created my own method.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int day = 1, month = 7, year = 2018;
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
//set the date with your date or the current date c.set(new Date());
c.set(year, month, day);
int diaSemana = c.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 7; i++) {
if (diaSemana != Calendar.MONDAY) {
day--;
c.set(year, month, day);
diaSemana = c.get(Calendar.DAY_OF_WEEK);
if (diaSemana == Calendar.MONDAY) break;
} else {
break;
}
}
String dateMonday= sdf.format(c.getTime());

Kotlin code. Works in older android versions
val c = Calendar.getInstance()
c.time = Date()
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DAY_OF_WEEK, -1)
}

It won't work if the currents week monday is the month before... For example if today is Friday 1st of June... You should probably rather use the roll method...

Related

How to get starting date and end date of year in Android?

I need help in getting start and end date of current year, last year and next year.
Below is my code: this code is work fine for month, can I modify it for year?
Note: this code is only for example.
protected void getDataByMonths(int currentDayOfMonth) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month;
if (currentDayOfMonth >= 2) {
month = calendar.get(Calendar.MONTH) + 1;
} else {
month = calendar.get(Calendar.MONTH) - currentDayOfMonth;
}
int day = 1;
calendar.set(year, month, day);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
String firstday = String.valueOf(df.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth - 1);
String lastday = String.valueOf(df.format(calendar.getTime()));
String result = getButtonName(button) + " From :" + getDateInMonthFormat(firstday) + " " + "To :" + getDateInMonthFormat(lastday);
finalcontacts = mySqliteDBhelper.getContactsBetweenRange(button, getDateInMilliseconds(firstday), getDateInMilliseconds(lastday));
finalstatus.setText(result);
}
Assuming that you cannot use Java 8, here is how it could be done:
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Create first day of year
Calendar firstDayOfCurrentYear = Calendar.getInstance();
firstDayOfCurrentYear.set(Calendar.DATE, 1);
firstDayOfCurrentYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfCurrentYear.getTime()));
// Create last day of year
Calendar lastDayOfCurrentYear = Calendar.getInstance();
lastDayOfCurrentYear.set(Calendar.DATE, 31);
lastDayOfCurrentYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfCurrentYear.getTime()));
// Create first day of next year
Calendar firstDayOfNextYear = Calendar.getInstance();
firstDayOfNextYear.add(Calendar.YEAR, 1);
firstDayOfNextYear.set(Calendar.DATE, 1);
firstDayOfNextYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfNextYear.getTime()));
// Create last day of next year
Calendar lastDayOfNextYear = Calendar.getInstance();
lastDayOfNextYear.add(Calendar.YEAR, 1);
lastDayOfNextYear.set(Calendar.DATE, 31);
lastDayOfNextYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfNextYear.getTime()));
Output:
01/01/2016
12/31/2016
01/01/2017
12/31/2017
Check this:
public static String GetYearSlot(int option,String inputDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy",java.util.Locale.getDefault());
Date myDate = null;
try
{
myDate = sdf.parse(inputDate);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.YEAR, option);
calendar.set(Calendar.DAY_OF_YEAR, 1);
Date YearFirstDay = calendar.getTime();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
Date YearLastDay = calendar.getTime();
return sdf.format(YearFirstDay)+"-"+sdf.format(YearLastDay);
}
how to use:
GetYearSlot(1, fromDate): it gives you next year from the date you passed(input 1)
GetYearSlot(0, fromDate): it gives you current year from the date you passed(input 0)
GetYearSlot(-1, fromDate): it gives you previous year from the date you passed(input -1)
java.time
You are using troublesome old legacy date-time classes now supplanted by the java.time classes.
First get the current 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.
ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );
Use Year to represent the entire year as an object.
Year thisYear = Year.from( today );
Year nextYear = thisYear.plusYears( 1 );
Year lastYear = thisYear.minusYears( 1 );
Usually in date-time work we represent a span of time using the Half-Open approach. In this approach the beginning is inclusive while the ending is exclusive. So a year would start on January first and run up to, but not include, January 1 of the following year.
If on Java 8, you could include the ThreeTen-Extra project and its Interval class to represent the span of time.
Otherwise do it yourself.
LocalDate thisYearStart = thisYear.atDay( 1 );
LocalDate lastYearStart = lastYear.atDay( 1 );
LocalDate nextYearStart = nextYear.atDay( 1 );
If you truly need the last day of the year, you could just subtract one day from the first day of the following year. Even easier is using a TemporalAdjuster defined in TemporalAdjusters class.
LocalDate thisYearFirstDay = today.with( TemporalAdjusters.firstDayOfYear() );
LocalDate thisYearLastDay = today.with( TemporalAdjusters.lastDayOfYear() );
LocalDate nextYearFirstDay = thisYearLastDay.plusDays( 1 );
LocalDate nextYearLastDay = nextYearFirstDay.with( TemporalAdjusters.lastDayOfYear() );
LocalDate lastYearLastDay = thisYearFirstDay.minusDays( 1 );
LocalDate lastYearFirstDay = lastYearLastDay.with( TemporalAdjusters.firstDayOfYear() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
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 (see How to use…).
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.

Getting dates after certain period of time in Java

Basically I have a date stored as text in this format: 16/09/2014 in SQLite Browser. I wonder is there any way to get the date after one day, one week, one month and one year of each records in the database using Java.
I retrieved and display the date retrieved from database in a listview:
viewHolder.txt_ddate.setText("Next Payment On: "
+ _recurlist.get(position).getRecurringStartDate().trim());
So I was thinking to use Java technique to get the dates I mentioned above. I have researched on this and found Documentation but I not sure how to implement it into my problem.
Any guides? Thanks in advance.
Use a Calendar object like in your example, which provides the add method.
String dateAsString = "16/09/2014";
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(formatter.parse(dateAsString));
c.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("After one day: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.DAY_OF_MONTH, -1);
c.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("After one week: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.WEEK_OF_YEAR, -1);
c.add(Calendar.MONTH, 1);
System.out.println("After one month: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.MONTH, -1);
c.add(Calendar.YEAR, 1);
System.out.println("After one year: " + formatter.format(c.getTimeInMillis()));
c.add(Calendar.YEAR, -1);
Output:
After one day: 17/09/2014
After one week: 23/09/2014
After one month: 16/10/2014
After one year: 16/09/2015
With Joda-time:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse("16/09/2014", formatter);
System.out.println(date.toString(formatter));
System.out.println(date.plusDays(1).toString(formatter));
System.out.println(date.plusWeeks(1).toString(formatter));
System.out.println(date.plusMonths(1).toString(formatter));
System.out.println(date.plusYears(1).toString(formatter));
Output:
16/09/2014
17/09/2014
23/09/2014
16/10/2014
16/09/2015
Use Calendar api of Java/Android as follow:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date;
try {
date = sdf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1); //add one day to your date
cal.add(Calendar.MONTH, 1); //add 1 month to your date
cal.add(Calendar.YEAR, 1); //add 1 year to current date
System.out.println(sdf.format(cal.getTimeInMillis()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the example:
String strDate = "16/09/2014";
int noOfDays = 1;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, noOfDays);
tl;dr
LocalDate.parse(
"16/09/2014" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
.plusDays( 1 )
.format( DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
Details
Tip: Use date-time data types for date-time values. You should be using a date-oriented type to define your column in your database to store a date value rather than as text.
Tip # 2: When you do serialize a date value to text, use the standard ISO 8601 formats. These are sensible, practical, and sort chronologically when alphabetical.
Use the java.time classes rather than the troublesome old date-time classes that are now legacy. For Android, see bullets below.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( "16/09/2014" , f ) ;
LocalDate dayAfter = ld.plusDays( 1 ) ;
LocalDate weekAfter = ld.plusWeeks( 1 ) ;
LocalDate monthAfter = ld.plusMonths( 1 ) ;
LocalDate yearAfter = ld.plusYears( 1 ) ;
To generate a string in standard format, simply call toString.
String output = dayAfter.toString() ; // YYYY-MM-DD standard format.
2014-09-17
For other formats, use a DateTimeFormatter as seen above.
String output = dayAfter.format( f ) ;
17/09/2014
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….

Get the last day of next three weeks Java

I want to get the last day of next three weeks.
For example,if today is Wednesday,16 April ,I will get the result Sunday,4 May.
I have written a function like this
public static Date nexThreeWeekEnd() {
Date now = new Date();
Date nextWeeks = DateUtils.truncate(DateUtils.addWeeks(now, 3), Calendar.DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(nextWeeks);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_WEEK));
return calendar.getTime();
}
DateUtils is used from this library:
org.apache.commons.lang.time.DateUtils;
But this function will return Wednesday, 7 May, that's mean it will return exactly the day of current date.
It's not necessary to rewrite my function. Any other ways to solve my problem will be very appriciated.
Thanks.
Use below code hope it helps
Calendar cal = Calendar.getInstance();
int currentDay = cal.get(Calendar.DAY_OF_WEEK);
int leftDays= Calendar.SUNDAY - currentDay;
cal.add(Calendar.DATE, leftDays)
Just try with:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
c.add(Calendar.WEEK_OF_YEAR, 2);
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df.format(c.getTime()));
Output:
2014/05/04
You can do something like this:
Calendar calendar = Calendar.getInstance().getFirstDayOfWeek();
calendar.add(Calendar.WEEK_OF_YEAR, 4);
calendar.add(Calendar.DAY_OF_MONTH, -1);
IN Java we can make use of Gregorian calendar
please check if below code helps you
Date d = new Date();
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(d);
System.out.println(cal1.getTime());
int day = cal1.get(Calendar.DAY_OF_WEEK );
cal1.add(Calendar.DAY_OF_YEAR,-(day-1));/*go to start of the week*/
cal1.add(Calendar.WEEK_OF_YEAR,3); // add 3 weeks
day = cal1.get(Calendar.DAY_OF_MONTH );// get the end Day of the 3rd week
System.out.println("end of the 3rd week ="+day);
The Question and other Answers use old outmoded classes.
java.time
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. See Oracle Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The LocalDate class represents a date-only value without time-of-day and time zone. You can use a TemporalAdjuster to generate a new LocalDate value relative to the original. The TemporalAdjusters (note the plural) class implements several handy such adjusters includning the one we need, nextOrSame( WeekOfDay ). The WeekOfDay class is a handy enum representing each of the seven days of the week, Monday-Sunday.
LocalDate start = LocalDate.of ( 2014 , Month.APRIL , 16 );
LocalDate nextOrSameSunday = start.with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ) );
LocalDate twoWeeksAfterNextOrSameSunday = nextOrSameSunday.plusWeeks ( 2 );
Dump to console.
System.out.println ( "start: " + start + " | nextOrSameSunday: " + nextOrSameSunday + " | twoWeeksAfterNextOrSameSunday: " + twoWeeksAfterNextOrSameSunday );
start: 2014-04-16 | nextOrSameSunday: 2014-04-20 | twoWeeksAfterNextOrSameSunday: 2014-05-04

Changing Java Date one hour back

I have a Java date object:
Date currentDate = new Date();
This will give the current date and time. Example:
Thu Jan 12 10:17:47 GMT 2012
Instead, I want to get the date, changing it to one hour back so it should give me:
Thu Jan 12 09:17:47 GMT 2012
What would be the best way to do it?
java.util.Calendar
Calendar cal = Calendar.getInstance();
// remove next line if you're always using the current time.
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();
java.util.Date
new Date(System.currentTimeMillis() - 3600 * 1000);
org.joda.time.LocalDateTime
new LocalDateTime().minusHours(1)
Java 8: java.time.LocalDateTime
LocalDateTime.now().minusHours(1)
Java 8 java.time.Instant
// always in UTC if not timezone set
Instant.now().minus(1, ChronoUnit.HOURS));
// with timezone, Europe/Berlin for example
Instant.now()
.atZone(ZoneId.of("Europe/Berlin"))
.minusHours(1));
Similar to #Sumit Jain's solution
Date currentDate = new Date(System.currentTimeMillis() - 3600 * 1000);
or
Date currentDate = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));
tl;dr
In UTC:
Instant.now().minus( 1 , ChronoUnit.HOURS )
Or, zoned:
Instant.now()
.atZone( ZoneId.of ( "America/Montreal" ) )
.minusHours( 1 )
Using java.time
Java 8 and later has the new java.time framework built-in.
Instant
If you only care about UTC (GMT), then use the Instant class.
Instant instant = Instant.now ();
Instant instantHourEarlier = instant.minus ( 1 , ChronoUnit.HOURS );
Dump to console.
System.out.println ( "instant: " + instant + " | instantHourEarlier: " + instantHourEarlier );
instant: 2015-10-29T00:37:48.921Z | instantHourEarlier: 2015-10-28T23:37:48.921Z
Note how in this instant happened to skip back to yesterday’s date.
ZonedDateTime
If you care about a time zone, use the ZonedDateTime class. You can start with an Instant and the assign a time zone, a ZoneId object. This class handles the necessary adjustments for anomalies such as Daylight Saving Time (DST).
Instant instant = Instant.now ();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
ZonedDateTime zdtHourEarlier = zdt.minus ( 1 , ChronoUnit.HOURS );
Dump to console.
System.out.println ( "instant: " + instant + "\nzdt: " + zdt + "\nzdtHourEarlier: " + zdtHourEarlier );
instant: 2015-10-29T00:50:30.778Z
zdt: 2015-10-28T20:50:30.778-04:00[America/Montreal]
zdtHourEarlier: 2015-10-28T19:50:30.778-04:00[America/Montreal]
Conversion
The old java.util.Date/.Calendar classes are now outmoded. Avoid them. They are notoriously troublesome and confusing.
When you must use the old classes for operating with old code not yet updated for the java.time types, call the conversion methods. Here is example code going from an Instant or a ZonedDateTime to a java.util.Date.
java.util.Date date = java.util.Date.from( instant );
…or…
java.util.Date date = java.util.Date.from( zdt.toInstant() );
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.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 1);
Or using the famous Joda Time library:
DateTime dateTime = new DateTime();
dateTime = dateTime.minusHours(1);
Date modifiedDate = dateTime.toDate();
Just subtract the number of milliseconds in an hour from the date.
currentDate.setTime(currentDate.getTime() - 3600 * 1000));
You can use from bellow code for date and time :
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 1);
System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 1);
System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 1);
System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -1);
System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, -1);
System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));
Output :
Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52
This link is good : See here
And see : See too
And : Here
And : Here
And : Here
If you need just time :
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
This can be achieved using java.util.Date. The following code will subtract 1 hour from your date.
Date date = new Date(yourdate in date format);
Date newDate = DateUtils.addHours(date, -1)
Similarly for subtracting 20 seconds from your date
newDate = DateUtils.addSeconds(date, -20)
To subtract hours, you need to use the HOUR_OF_DAY constant. Within that, include the number with the negative sign. This would be the hours you want to reduce. All this is done under the Calendar add() method.
The following is an example:
import java.util.Calendar;
public class Example {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
System.out.println("Date : " + c.getTime());
// 2 hours subtracted
c.add(Calendar.HOUR_OF_DAY, -2);
System.out.println("After subtracting 2 hrs : " + c.getTime());
}
}
Here is the output:
Date : Sun Dec 16 16:28:53 UTC 2018
After subtracting 2 hrs : Sun Dec 16 14:28:53 UTC 2018
Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!
int minutes = 60;
long currentDateTime = System.currentTimeMillis();
Date currentDate = new Date(currentDateTime - minutes*60*1000);
System.out.println(currentDate);
It worked for me instead using format .To work with time just use parse and toString() methods
String localTime="6:11";
LocalTime localTime = LocalTime.parse(localtime)
LocalTime lt = 6:11;
localTime = lt.toString()

Finding day of a date in Java

I want to find out the day of the date in Java for a date like 27-04-2011.
I tried to use this, but it doesn't work:
Calendar cal = Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_WEEK);
It gives the integer value, not the String output I want. I am not getting the correct value I want. For example it is giving me value 4 for the date 28-02-2011 where it should be 2 because Sunday is the first week day.
Yes, you've asked it for the day of the week - and February 28th was a Monday, day 2. Note that in the code you've given, you're not actually setting the date anywhere - it's just using the current date, which is a Wednesday, which is why you're getting 4. If you could show how you're trying to set the calendar to a different date (e.g. 28th of February) we can work out why that's not working for you.
If you want it formatted as text, you can use SimpleDateFormat and the "E" specifier. For example (untested):
SimpleDateFormat formatter = new SimpleDateFormat("EEE");
String text = formatter.format(cal.getTime());
Personally I would avoid using Calendar altogether though - use Joda Time, which is a far superior date and time API.
Calendar cal=Calendar.getInstance();
System.out.println(new SimpleDateFormat("EEE").format(cal.getTime()));
Output
Wed
See Also
SimpleDateFormat
String dayNames[] = new DateFormatSymbols().getWeekdays();
Calendar date1 = Calendar.getInstance();
System.out.println("Today is a "
+ dayNames[date1.get(Calendar.DAY_OF_WEEK)]);
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String input = "27-04-2011";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-M-u", Locale.ENGLISH);
LocalDate date = LocalDate.parse(input, dtf);
DayOfWeek dow = date.getDayOfWeek();
System.out.println(dow);
// String value
String strDay = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println(strDay);
strDay = dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println(strDay);
// Alternatively
strDay = date.format(DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH));
System.out.println(strDay);
strDay = date.format(DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH));
System.out.println(strDay);
}
}
Output:
WEDNESDAY
Wednesday
Wed
Wednesday
Wed
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
See the JavaDoc of the DAY_OF_WEEK field. It points to 7 constants SUNDAY..SATURDAY that show how to decode the int return value of cal.get(Calendary.DAY_OF_WEEK). Are you sure that
Calendar cal = Calendar.getInstance();
cal.set(2011, 02, 28);
cal.get(Calendar.DAY_OF_WEEK);
returns the wrong value for you?
Try following:
Calendar cal=Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(new DateFormatSymbols().getWeekdays()[val]);
or
Calendar cal=Calendar.getInstance();
String dayName = new DateFormatSymbols().getWeekdays()[cal
.get(Calendar.DAY_OF_WEEK)];
System.out.println(dayName);
Calendar cal=Calendar.getInstance();
cal.set(2011, 2, 28);
int val = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(val);
Look at SimpleDateFormat and propably Locale.
If you need the exact date value in the month you need to use Calendar:DAY_OF_MONTH it will return the exact date in the month starting from 1.
//Current date is 07-06-2021 and this will return 7
Calendar cal = Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in month:"+val);
//If you want the day of the week in text better use the
//SimpleDateFormat, since Calendar API will return the integer value in
// the week if we given Calendar.DAY_OF_WEEK
String dayWeekText = new SimpleDateFormat("EEEE").format(cal.getTime());
System.out.println("Day of week:"+dayWeekText);
As suggested in the comment Java Date API have all these feature available. Java 8 introduced new APIs for Date and Time to address the shortcomings of the older java.util.Date and java.util.Calendar.
The same can be achieved using Date API in Java
LocalDate localDate = LocalDate.parse("2021-06-08"); //2021 June 08 Tuesday
System.out.println(localDate.dayOfWeek().getAsText()); //Output as : Tuesday
System.out.println(localDate.dayOfWeek().getAsShortText()); //Output as : Tue
System.out.println(localDate.dayOfMonth().get()); //Output as current date

Categories