How to get previous date in java/joda-time excluding week ends - java

I am using this code to get previous date but i would like to get the date excluding Saturday and Sunday
the code that i use to get previous date :
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
public static void main(String[] args) {
String dateString = "2012-08-20";
try {
// This will print 2012-08-19
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}`
It works fine but need to get the previous date which is not Saturday or Sunday.
Regards

You should have to get DAY_OF_WEEK from the calendar object and if its next day is MONDAY then subtract three days or if SUNDAY then subtract two days from the date/calendar object.
calendar.setTime(myDate);
int dayOfWeek=calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek==Calendar.MONDAY)
calendar.add(Calendar.DAY_OF_YEAR, -3);
else
if(dayOfWeek==Calendar.SUNDAY)
calendar.add(Calendar.DAY_OF_YEAR, -2);
else
calendar.add(Calendar.DAY_OF_YEAR, -1);

Related

Java - Calendar.getTime does not retrieve the date set with Calendar.setTime

I have the following code in Java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
public static void main(String[] args) {
try {
SimpleDateFormat SDF = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss");
Calendar date = Calendar.getInstance();
date.setTime(SDF.parse("2011-02-01T00:00:00"));
System.out.println(SDF.format(date.getTime()));
} catch (Exception e) {
}
}
}
I expect to see in the console the following string
2011-02-01T00:00:00
instead I see
2011-12-26T00:00:00
What can be wrong?
I change the format: "yyyy-MM-dd'T'HH:mm:ss"
SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar date = Calendar.getInstance();
date.setTime(SDF.parse("2011-02-01T00:00:00"));
System.out.println(SDF.format(date.getTime()));
The output is 2011-02-01T00:00:00
"Y": week year
"y": year
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
From the documentation:
"If week year 'Y' is specified and the calendar doesn't support any week years, the calendar year ('y') is used instead. The support of week years can be tested with a call to getCalendar().isWeekDateSupported()."
In some calendar "Y" and "y" are the same, but is not the case of the gregorian calendar.
https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#isWeekDateSupported%28%29

Wrong last day of month

Where is some function to get the last day of month in my service?
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = format.parse(stringDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(lastDayOfMonth);
So, this method correctly works elsewhere, but in US last day is always 29 (last day - 1)
stringDate is date in format "yyyy-MM-dd"
I believe this problem is due to Day Light saving time in US.
You can change this by setting the Timezone for Calendar to different timezone.
Related question: Adding days with java.util.Calendar gives strange results
Java Date has very poor API. Instead of this I would recommend you to use Joda Time.
In Joda it would look like this:
LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();
If you don't have Java 8, this is very compact with JodaTime.
import org.joda.time.DateTime;
public class SoLastDay {
public DateTime lastDay(final String yyyy_MM_dd) {
DateTime givenDate = new DateTime(yyyy_MM_dd);
return givenDate.dayOfMonth().withMaximumValue();
}
}
And a small test...
#Test
public void testLastDay() throws Exception {
SoLastDay soLastDay = new SoLastDay();
String date1 = "2015-01-27";
System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1).toString("yyyy-MM-dd"));
String date2 = "2015-02-02";
System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2).toString("yyyy-MM-dd"));
}
And the test results:
Date 2015-01-27 becomes 2015-01-31.
Date 2015-02-02 becomes 2015-02-28.
If you do have Java 8, you might use code like this:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class SoLastDayJava8 {
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public LocalDate lastDay(final String yyyy_MM_dd) {
LocalDate givenDate = LocalDate.parse(yyyy_MM_dd, formatter);
return givenDate.with(TemporalAdjusters.lastDayOfMonth());
}
}
The test code changes just a bit.
public class SoLastDayJava8Test {
#Test
public void testLastDay() throws Exception {
SoLastDayJava8 soLastDay = new SoLastDayJava8();
String date1 = "2015-01-27";
System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1));
String date2 = "2015-02-02";
System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2));
}
}
But the results are the same.
Date 2015-01-27 becomes 2015-01-31.
Date 2015-02-02 becomes 2015-02-28.
You are messing with the TimeZones.
When you execute Date date = format.parse(stringDate); you are creating a Date object with the TimeZone of the DateFormat object. Theoretically if the TimeZone is the same for all your DateFormat and Calendar objects, you should be fine. Check if they are coherent with the getTimeZone() method.
If the TimeZone of the first DateFormat is wrong (e.g. is your TimeZone or UTC or GMT), you'll get a UTC-008 conversion in the second TimeZone (and in the Calendar) resulting in the missing day since you start from midnight.
Judging from your code is the stringDate itself that has been wrongly converted somewhere else...

How to get data in java with localization?

I have table with data of date.
This is how I calcaulted the date
DateFormat dateFormat = getFormat();
date = dateFormat.parse((String) value).getTime();
if(date != null) {
cell.setValue(dateFormat.format(date));
tableViewer.update(element, null);
}
public static DateFormat getFormat() {
String systemLocale = System.getProperty("user.language"); //$NON-NLS-1$
Locale locale = new Locale(systemLocale);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
return dateFormat;
}
The date is exist in the screen in format Month(name of the month) date, year
for example Apr 26,2014.
Now I want to get the value of the cell and to get to format of 'yyyy-mm-dd'
The value of the date is Apr 26,2014.
How I can get the result of 2014-04-26 ? also I think that the value in the UI could change according to the localization of the user
I tried
DateFormat dateFormat = getFormat();
Date parse = dateFormat.parse((String) key);
but then all the get method are deprecated and also I didn't get right result for getYear
I am not expert in the date maybe I miss something
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CustomFormattedDate {
public static void main(String[] args) {
Date date = new Date();
// if you use DD for Daypattern, you'll get the day of the year, e.g. 119 for the
// 29th April 2014, if you want 29, the day of the month, use dd
SimpleDateFormat df = new SimpleDateFormat("YYYY-dd-MMM", new Locale(System.getProperty("user.language")));
System.out.println(df.format(date));
System.out.println(getDateFormat().format(date));
}
}
Output
2014-29-Apr

Error in Retrieving Year Month Date from Calender object

All this is my program where i am trying the folowing
Below is my code for Dates functionality...
import java.text.SimpleDateFormat;
import java.util.*;
import java.text.*;
public class DateToCalender {
public static void main(String args[]){
//String strFormat="yyyymmdd";
//DateFormat myDateFormat = new SimpleDateFormat(strFormat);
DateFormat df= new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
Calendar start=Calendar.getInstance();
try {
Date fromDt =(Date)df.parse("20111207");
//Date myDate = new Date();
//myDate = (Date)myDateFormat.parse("20111207");
//myGDate.setTime(myDate);
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)+1));
System.out.println(start);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)-1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
//System.out.println("From My class"+myGDate.get(Calendar.MONTH));
//System.out.println("From My class new month"+(myGDate.get(Calendar.MONTH)+1));
} catch (ParseException e) {
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
}
when iam executing this code iam getting folowwing o/p
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA
=1,YEAR=2011,MONTH=12,WEEK_OF_YEAR=50,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=341,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0]
2011
0
7
**
issue is :
Though iam entering date as 2011/12/07
I am getting year as 2011
month as 0
date as 7
Can some one help in resolving above issue
Could any body please let me know , how this can be resolved .
Don't subtract 1 from the month; Calendar already knows that it's zero-based.
It seems to me like you're doing far too much work here. Why can't you just do this?
private static final DateFormat DEFAULT_DATE_FORMAT;
static {
DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
DEFAULT_DATE_FORMAT.setLenient(false);
}
public Calendar getCalendar(String dateAsString) {
Calendar value = Calendar.getInstance();
Date d = DEFAULT_DATE_FORMAT.parse(dateAsString);
value.setTime(d);
return value;
}
There's an exception that needs to be added to the method signature, but you get the idea. Look at the Calendar javadocs. This could be easier.
setting a condition to check the month can resolve your problem:
try {
Date fromDt =(Date)df.parse("20131209");
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)));
int month = start.get((Calendar.MONTH));
if (month ==11){
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)+1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}else{
start.set(Calendar.MONTH,(start.get(Calendar.MONTH))+1);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH));
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}
}
this will print out :
2013
12
9

Date function in java

I have two dates
1) from_date: eg. 01/01/2010 (1st January 2010)
2) present_date: eg. 05/06/2011 (5th June 2011)
I want the third date as:
3) req_date: eg. 01/01/2011(1st January 2011)
Year should come from "present_date" and day and month should come from "from_date".
The dates which I mentioned are hardCoded.
In my code, I run a query to get these 2 dates.
Look into the Calendar class
http://www.java-examples.com/add-or-substract-days-current-date-using-java-calendar
Something like // Untested
Calendar cal=Calendar.getInstance();
cal.setTime(from_date);
Calendar cal2=Calendar.getInstance();
cal2.setTime(present_date);
Calendar cal3=Calendar.getInstance();
cal3.set(cal2.get(CALENDAR.YEAR),cal1.get(CALENDAR.MONTH),cal1.get(CALENDAR.DATE));
Date reg_date = cal3.getTime();
You can set individual fields of dates:
Date req_date = from_date;
req_date.setYear (present_date.getYear());
Or, if you're using Calendar (Date is deprecated):
Calendar req_date = from_date;
req_date.set (YEAR, present_date.get(YEAR));
If they're strings, you can just use substringing to get what you want:
String req_date = from_date.substring(0,6) + present_date.substring(6);
(assuming XX/XX/YYYY as seems to be the case).
Not sure if I understand you correctly but this example should get you started:
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
this way you can convert date Strings to java.util.Date object, then you can construct the third date by using Date/Calendar methods
from_date: for EX. 01/01/2010 (1 st January 2010)
present_date :for EX. 05/06/2011(5th june 2011)
String s1[]=from_date.split("/");
String s2[]=present_date.split("/");
String newDate=s1[0]+"/"+s1[1]+"/"+s2[2];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}

Categories

Resources