how to get date of last two Fridays from today? - java

I need to get the dates of last two Fridays using today's date.This is the code I'm currently using
public class GetDate {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
System.out.println("today : " + sdf.format(dt));
while (c.get(Calendar.DAY_OF_WEEK) != 6) {
c.add(Calendar.DATE, -1);
}
Date lastFri=c.getTime();
System.out.println("last fri : "+sdf.format(lastFri));
c.add(Calendar.DATE, -7);
Date prevFri = c.getTime();
System.out.println("previous friday : "+sdf.format(prevFri));
}
}
Is there any way to optimize this code??

With Java 8, and if you don't have to use the Calendar api, you can use a TemporalAdjuster:
LocalDate today = LocalDate.now();
LocalDate prevFriday = today.with(previous(FRIDAY));
LocalDate prevPrevFriday = prevFriday.with(previous(FRIDAY));
note: requires the following static import
import static java.time.temporal.TemporalAdjusters.previous;
import static java.time.DayOfWeek.FRIDAY;

You could get the last Friday this way :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
This gets the last Friday by subtracting a week and setting the day of week to Friday.

Try something like:
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Date lastFriday = cal.getTime();
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Date lastToLastFriday = cal.getTime();

This line should help:
calendar.add(Calendar.DATE, Calendar.FRIDAY - 7 - c.get(Calendar.DAY_OF_WEEK));
So this code is solving your problem:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = GregorianCalendar.getInstance();
c.add(Calendar.DATE, Calendar.FRIDAY - 7 - c.get(Calendar.DAY_OF_WEEK));
System.out.println(sdf.formate(c.getTime()));
c.add(Calendar.DATE, Calendar.FRIDAY - 14 - c.get(Calendar.DAY_OF_WEEK));
System.out.println(sdf.formate(c.getTime()));

Related

How can i increment my date by 1

I want to increment the date by one. I have the below code while running the code I am getting unparseable date finally I want the date as string in the format of MM-DD-YYYY.
But same program is working with the YYYY-MM-DD format but i want mydate in this format(MM-DD-YYYY)
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);
Can anyone please help me?
The code should be working fine as long as dt and days are correct. This gave me 12-18-2014:
String dt = "12-17-2014"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-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 have to use two different DateFormats:
one for parsing the string and one for formatting.
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf_parser = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf_parser.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);

Formatting java.sql.Date to yyyyMMdd

I am using the below code
#SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
I am getting below output.
3914-02-09
39140209
Does any one know why there is 3914?
Thanks,
Mahesh
The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
so you should use (assuming you mean this year)
Date d = new Date (2015-1900,01,9);
From Java Docs,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Code
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
output
2014-01-09

Calendar offset issue

I need to get the month and day of today's date and offset dates. This is how I do it:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_WEEK, 0);
Date today = calendar.getTime();
System.out.println(today);
Output:
Wed Aug 27 15:07:35 CEST 2014
Two things, I need the month and the day to be numeric, like 8/27. I understand how to do that with today's date like so:
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
String a = String.valueOf(day);
String b = String.valueOf(month);
System.out.println(b +"/" + a);
My issue is that I might need to add an offset to that date, if I want tomorrows date for example. Is there a way to do that because converting Wed Aug 27.... to 8/27 would just be a pain. Thanks
Use simple date format:
Something like:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_WEEK, 1);
Date today = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(today));
DateFormat formatter = new SimpleDateFormat("MM/dd");
Calendar cal = Calendar.getInstance();
String calAsString = formatter.format(cal.getTime());
System.out.println(calAsString);
// Now for tomorrow's date:
int offset = 1;
cal.add(Calendar.DATE, offset);
calAsString = formatter.format(cal.getTime());
System.out.println(calAsString);
Use the Calendar to add a value to the day:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH,1)

Get yesterday's date using Date [duplicate]

This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
The following function produces today's date; how can I make it produce only yesterday's date?
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date).toString();
}
This is the output:
2012-07-10
I only need yesterday's date like below. Is it possible to do this in my function?
2012-07-09
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
https://ideone.com/91M1eU
Outdated answer
You are subtracting the wrong number:
Use Calendar instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
IDEOne Demo
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
Try this one:
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Create a calendar object with today date. Calendar is in java.util pakage.
Calendar calendar = Calendar.getInstance();
// Move calendar to yesterday
calendar.add(Calendar.DATE, -1);
// Get current date of calendar which point to the yesterday now
Date yesterday = calendar.getTime();
return dateFormat.format(yesterday).toString();
}
Try this;
public String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar by subtracting -1.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Java - How to calculate the first and last day of each week

I'm trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html
How can I calculate every week date? For example, this week is:
Monday - Sunday
7 June, 8 June, 9 June, 10 June, 11 June, 12 June, 13 June
I guess this does what you want:
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
With the new date and time API in Java 8 you would do:
LocalDate now = LocalDate.now();
// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));
// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));
// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
System.out.println(printDate.format(formatter));
printDate = printDate.plusDays(1);
}
Java.time
Using java.time library built into Java 8:
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
LocalDate now = LocalDate.now(); # 2015-11-23
LocalDate first = now.with(previousOrSame(DayOfWeek.MONDAY)); # 2015-11-23
LocalDate last = now.with(nextOrSame(DayOfWeek.SUNDAY)); # 2015-11-29
You can iterate over DayOfWeek.values() to get all current week days
DayOfWeek.values(); # Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
for (DayOfWeek day: DayOfWeek.values()) {
System.out.print(first.with(nextOrSame(day)));
} # 2015-11-23, 2015-11-24, 2015-11-25, 2015-11-26, 2015-11-27, 2015-11-28, 2015-11-29
First day of this week.
Calendar c = Calendar.getInstance();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DATE, -1);
}
Simply setting the day of week does not seem to be reliable. Consider the following simple code:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n", calendar);
System.out.printf("First day of week: %d%n", calendar.getFirstDayOfWeek());
The result of running this program is:
Starting day: 2011-09-18
Last monday: 2011-09-19
First day of week: 2
In other words, it stepped forward in time. For a German locale, this is really not the expected answer. Note that the calendar correctly uses Monday as first day of the week (only for computing the week of the year, perhaps).
You can build up on this: The following code prints the first and last dates of each week for 15 weeks from now.
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for(int i=0; i<15; i++)
{
System.out.print("Start Date : " + c.getTime() + ", ");
c.add(Calendar.DAY_OF_WEEK, 6);
System.out.println("End Date : " + c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
}
If you know which day it is (Friday) and the current date (June 11), you can calculate the other days in this week.
I recommend that you use Joda Time library. Gregorian Calendar class has weekOfWeekyear and dayOfWeek methods.
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(endDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
while (startCal.before(endCal)) {
int weekNumber = startCal.get(Calendar.WEEK_OF_YEAR);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date sunday = cal.getTime();
Log.d("sunday", "" + sdf.format(sunday));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date saturday = cal.getTime();
Log.d("saturday", "" + sdf.format(saturday));
weekNumber = weekNumber + 1;
startCal.set(Calendar.WEEK_OF_YEAR, weekNumber);
}
Yes. Use Joda Time
http://joda-time.sourceforge.net/
The algorithm you're looking for (calculating the day of the week for any given date) is "Zeller's Congruence". Here's a Java implementation:
http://technojeeves.com/joomla/index.php/free/57-zellers-congruence

Categories