I have jdk java version "1.8.0_45", i am using joda time api (joda-time-2.7.jar)
By using Joda time api i am getting a wrong date.
By using Jdk 8 hijri date api i am getting a correct date.
I have a requirement to convert a gregorian date to hijri date using java api.
My sample test class is as follows:
import org.joda.time.*;
import org.joda.time.chrono.*;
import java.time.*;
import java.time.chrono.HijrahChronology;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTime dtISO = new DateTime();
System.out.println("dtISO = "+dtISO);
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance(DateTimeZone.UTC ));
System.out.println(dtIslamic.getYear()+"-" +dtIslamic.getMonthOfYear()+ "-"+ dtIslamic.getDayOfMonth());
java.time.chrono.HijrahDate hijradate = java.time.chrono.HijrahDate.now();
System.out.println("hijradate "+hijradate);
}
}
Output of this class is
C:\>java Test
dtISO = 2015-05-24T09:44:51.704+04:00
1436-8-5
hijradate Hijrah-umalqura AH 1436-08-06
Can you please tell me joda api is correct one or wrong one?
My production server has JDK1.6 i cannot upgrade it to 1.8 as of now, so kindly let me know your suggestions to get a proper hijri date .... Awaiting for your reply....
The difference you are seeing between JodaTime and JDK8 is because they use different implementations of the Hijri Calendar. There are multiple algorithms to compute (approximate) a Hijri date.
Jdk8's HijrahChoronology uses an implementation of Umm-AlQura calendar which closely matches the official Hijri calendar in Saudi Arabia as defined in http://www.ummulqura.org.sa/.
JodaTime IslamicChronology has different implementations which you can select from using its factory methods see http://joda-time.sourceforge.net/apidocs/org/joda/time/chrono/IslamicChronology.html
So it really depends on system audience. If you are in Saudi Arabia or any country which relies on UmmAlQura calendar stick with the JDK8's implementation.
i found this code on http://junaedhalim.blogspot.com/2010/01/hijri-calendar-in-java-using-kuwaiti.html hopefully it help you
import java.util.Calendar;
import java.util.Date;
/**
*
* #author junaed
*/
public class HijriCalendar
{
private int[] userDateG;
private int[] userDateH;
private WaqtMidlet midlet;
private Calendar cal;
private int currentHijriDate;
private int currentHijriMonth;
private int currentHijriYear;
public static final String[] HIJRI_MONTHS =
{
"Muharram", "Safar", "Rabi' al-awwal", "Rabi' al-thani", "Jumada al-awwal",
"Jumada al-thani", "Rajab", "Sha'aban", "Ramadan", "Shawwal", "Dhu al-Qi'dah", "Dhu al-Hijjah"
};
public static final int[] BASE_DATE_G =
{
18, 11, 2009, 0, 0
};
public static final int[] BASE_DATE_H =
{
1, 0, 1431, 0, 0
};
public HijriCalendar(WaqtMidlet midlet)
{
this.midlet = midlet;
cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
}
private void updateDefinedTime()
{
String uTimeH = midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
// String uTimeH = "";
if (uTimeH == null || uTimeH.equalsIgnoreCase(""))
{
userDateG = ApplicationConstants.BASE_DATE_G;
userDateH = ApplicationConstants.BASE_DATE_H;
}
else
{
System.out.println("uTimeH = " + uTimeH);
int date = Integer.parseInt(uTimeH.substring(0, uTimeH.indexOf(';')));
String rest = uTimeH.substring(uTimeH.indexOf(';') + 1);
int month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int hour = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int minute = Integer.parseInt(rest);
userDateH = new int[]
{
date, month, year, hour, minute
};
// String uTimeG = "";
String uTimeG = midlet.getRmsManager().getString(ApplicationConstants.RMS_GREGORIAN_DATE);
System.out.println("uTimeG = " + uTimeG);
date = Integer.parseInt(uTimeG.substring(0, uTimeG.indexOf(';')));
rest = uTimeG.substring(uTimeG.indexOf(';') + 1);
month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
userDateG = new int[]
{
date, month, year, hour, minute
};
}
cal.set(Calendar.HOUR_OF_DAY, userDateG[3]);
cal.set(Calendar.MINUTE, userDateG[4]);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.DATE, userDateG[0]);
cal.set(Calendar.MONTH, userDateG[1]);
cal.set(Calendar.YEAR, userDateG[2]);
currentHijriDate = userDateH[0];
currentHijriMonth = userDateH[1];
currentHijriYear = userDateH[2];
}
private boolean isALeapYear(int year)
{
int modValue = year % 30;
switch (modValue)
{
case 2:
return true;
case 5:
return true;
case 7:
return true;
case 10:
return true;
case 13:
return true;
case 15:
return true;
case 18:
return true;
case 21:
return true;
case 24:
return true;
case 26:
return true;
case 29:
return true;
}
return false;
}
private int getDaysInThisYear(int year)
{
if (isALeapYear(year))
{
return 355;
}
return 354;
}
public int getDaysInThisMonth(int month, int year)
{
if (month % 2 != 0)
{
return 30;
}
else
{
if (month == 12)
{
if (isALeapYear(year))
{
return 30;
}
}
return 29;
}
}
private void addOneDayToCurrentDate()
{
currentHijriDate++;
if(currentHijriDate >= 29)
{
int daysInCurrentMonth = getDaysInThisMonth(currentHijriMonth, currentHijriYear);
if( currentHijriDate > daysInCurrentMonth)
{
currentHijriDate = 1;
currentHijriMonth++;
if(currentHijriMonth > 11)
{
currentHijriMonth = 1;
currentHijriYear++;
}
}
}
}
private void addDays(long days)
{
for(long i = 0; i< days; i++)
{
addOneDayToCurrentDate();
}
}
public String getCurrentDateStr()
{
updateDefinedTime();
Date date = new Date();
// int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
long diff = date.getTime() - cal.getTime().getTime();
long days = diff / (1000 * 86400);
addDays(days);
String ret = currentHijriYear + " "+HIJRI_MONTHS[currentHijriMonth] + ", " + currentHijriDate;
return ret;
// return midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
}
}
Try using ICU4J. Its Calendar classes do not extend java.util.Calendar, but they do properly deal with Hijri dates (and many other calendar systems). I was able to get what I believe are correct results using its IslamicCalendar class, using Java 1.6.0_31:
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.IslamicCalendar;
public class HijriDate {
public static void main(String[] args) {
java.util.Calendar gregorianCal =
java.util.Calendar.getInstance(Locale.US);
System.out.printf("%tF%n", gregorianCal);
Date date = gregorianCal.getTime();
Calendar cal = new IslamicCalendar();
cal.setTime(date);
System.out.printf("%02d-%02d-%02d%n",
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH));
}
}
Related
I'm using this Java code to get price based on month start and end date.
public int getPrice()
{
java.util.Date today = Calendar.getInstance().getTime();
Calendar aumgc = new GregorianCalendar();
aumgc.set(Calendar.AUGUST, 8);
aumgc.set(Calendar.DAY_OF_MONTH, 1);
java.util.Date augustStart = aumgc.getTime();
Calendar emgc = new GregorianCalendar();
emgc.set(Calendar.AUGUST, 8);
emgc.set(Calendar.DAY_OF_MONTH, 31);
java.util.Date augustEnd = emgc.getTime();
Calendar sepmgc = new GregorianCalendar();
sepmgc.set(Calendar.SEPTEMBER, 9);
sepmgc.set(Calendar.DAY_OF_MONTH, 1);
java.util.Date septemberStart = sepmgc.getTime();
Calendar eomgc = new GregorianCalendar();
eomgc.set(Calendar.SEPTEMBER, 9);
eomgc.set(Calendar.DAY_OF_MONTH, 31);
java.util.Date septemberEnd = eomgc.getTime();
Calendar ocmgc = new GregorianCalendar();
ocmgc.set(Calendar.OCTOBER, 10);
ocmgc.set(Calendar.DAY_OF_MONTH, 1);
java.util.Date octoberStart = ocmgc.getTime();
Calendar eocmgc = new GregorianCalendar();
eocmgc.set(Calendar.OCTOBER, 10);
eocmgc.set(Calendar.DAY_OF_MONTH, 31);
java.util.Date octoberEnd = eocmgc.getTime();
if (!(today.before(augustStart) || today.after(augustEnd)))
{
return 30;
}
if (!(today.before(septemberStart) || today.after(septemberEnd)))
{
return 40;
}
if (!(today.before(octoberStart) || today.after(octoberEnd)))
{
return 50;
}
return 0;
}
As you can see I'm using a lot of code to get the price based on current month. How I can simplify the code and use SQL date?
Is there any already made solution implemented in JVM?
I would suggest to use latest API LocalDateTime from Java 8 to do this king of thing, easily :
import java.time.Month; // Enum use in `switch` statement.
public int getPrice() {
LocalDateTime now = LocalDateTime.now(); // line 2
switch (now.getMonth()) { // line 3
case AUGUST:
return 30;
case SEPTEMBER:
return 40;
case OCTOBER:
return 50;
default:
return 0;
}
}
// line 2&3 can be reduce in : // switch (LocalDateTime.now().getMonth()){
This would return the same :
public int getPrice() {
return (LocalDateTime.now().getMonthValue() - 8) * 10 + 30;
}
//or return (LocalDateTime.now().getMonthValue() - 5) * 10;
I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public static int getAge. If the person is born after the current date i want it to print out error -1.
How do I compare the two SimpleDate values dateBd and dateRef in order to get an int value for age?
public static SimpleDate today() {
Calendar todayCal = Calendar.getInstance();
SimpleDate todayDate = new SimpleDate();
todayDate.setDate(todayCal.get(Calendar.MONTH) + 1,
todayCal.get(Calendar.DATE),
todayCal.get(Calendar.YEAR));
return todayDate;
public static int getAge(SimpleDate dateBd) {
int age;
SimpleDate dateToday = today();
age = getAge(dateBd, dateToday);
return age;
public static int getAge(SimpleDate dateBd, SimpleDate dateRef) {
if(getAge(dateBd)>getAge(dateRef)){
system.out.println("error");
}
return -1;
What is SimpleDate ? Anyway here something to get you started
import java.util.GregorianCalendar;
import java.util.Calendar;
public class CalcAge {
public static void main(String [] args) {
// remember ... months are 0-based : jan=0 feb=1 ...
System.out.println
("1962-11-11 : " + age(1962,10,11));
System.out.println
("1999-12-03 : " + age(1999,11,3));
}
private static int age(int y, int m, int d) {
Calendar cal = new GregorianCalendar(y, m, d);
Calendar now = new GregorianCalendar();
int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
res--;
}
return res;
}
}
Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.
Instead, save yourself (alot) of time and use a dedicated library
Java 8
LocalDate start = LocalDate.of(1972, Month.MARCH, 8);
LocalDate end = LocalDate.now();
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years);
Which outputs 43
JodaTime
DateTime startDate = new DateTime(1972, DateTimeConstants.MARCH, 8, 0, 0);
DateTime endDate = new DateTime();
Years y = Years.yearsBetween(startDate, endDate);
int years = y.getYears();
System.out.println(years );
Which outputs 43
You can even use a Period to gain more granuarlity...
Period period = new Period(startDate, endDate);
PeriodFormatter hms = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSeparator(" years, ")
.appendMonths()
.appendSeparator(" months, ")
.appendDays()
.appendLiteral(" days")
.toFormatter();
String result = hms.print(period);
System.out.println(result);
Which prints 43 years, 1 months, 5 days
I have a method that gets a string and change that to a particular date format but the thing is the date will be any format
For Example
16 July 2012
March 20 2012
2012 March 20
So I need to detect the string is in which file format.
I use the below code to test it but I get exception if the file format changes.
private String getUpdatedDate(String updated) {
Date date;
String formatedDate = null;
try {
date = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH)
.parse(updated);
formatedDate = getDateFormat().format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formatedDate;
}
Perhaps the easiest solution is to build a collection of date formats you can reasonably expect, and then try the input against each one in turn.
You may want to flag ambiguous inputs e.g. is 2012/5/6 the 5th June or 6th May ?
BalusC wrote a simple DateUtil which serves for many cases. You may need to extend this to satisfy your requirements.
Here is the link: https://balusc.omnifaces.org/2007/09/dateutil.html
and the method you need to look for determineDateFormat()
If you're using Joda Time (awesome library btw) you can do this quite easily:
DateTimeParser[] dateParsers = {
DateTimeFormat.forPattern("yyyy-MM-dd HH").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, dateParsers).toFormatter();
DateTime date1 = formatter.parseDateTime("2012-07-03");
DateTime date2 = formatter.parseDateTime("2012-07-03 01");
Apache commons has a utility method to solve this problem . The org.apache.commons.lang.time.DateUtils class has a method parseDateStrictly
public static Date parseDateStrictly(String str,
String[] parsePatterns)
throws ParseException
Parameters:
str - the date to parse, not null
parsePatterns - the date format patterns to use, see SimpleDateFormat, not null
Parses a string representing a date by trying a variety of different parsers.
The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.
The parser parses strictly - it does not allow for dates such as "February 942, 1996".
FTA (https://github.com/tsegall/fta) is designed to solve exactly this problem (among others). Here is an example:
import java.util.Locale;
import com.cobber.fta.dates.DateTimeParser;
import com.cobber.fta.dates.DateTimeParser.DateResolutionMode;
public abstract class DetermineDateFormat {
public static void main(final String[] args) {
final DateTimeParser dtp = new DateTimeParser(DateResolutionMode.MonthFirst, Locale.ENGLISH);
System.err.println(dtp.determineFormatString("26 July 2012"));
System.err.println(dtp.determineFormatString("March 9 2012"));
// Note: Detected as MM/dd/yyyy despite being ambiguous as we indicated MonthFirst above when insufficient data
System.err.println(dtp.determineFormatString("07/04/2012"));
System.err.println(dtp.determineFormatString("2012 March 20"));
System.err.println(dtp.determineFormatString("2012/04/09 18:24:12"));
}
Which will give the following output:
MMMM d yyyy
MM/dd/yyyy
yyyy MMMM dd
yyyy/MM/dd HH:mm:ss
Decide which formats are expected, and try to parse the date with each format, one after the other. Stop as soon as one of the formats parses the date without exception.
Click to see the result
Use the regex to parse the string for date. This regex can detect any kind of date format. The sample code here is not including time yet. You can change the code to add more parts of the date like time and time zone...The month name is depending on default language locale of the system.
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateUtils {
static String MONTH="";
static String dateRegEx="";
static Pattern DatePattern;
static HashMap<String, Integer> monthMap = new HashMap<String, Integer>();
static {
initializeMonthName();
dateRegEx="(?i)(\\d{1,4}|"+MONTH+")[-|/|.|\\s+]?(\\d{1,2}|"+MONTH+")[-|/|.|,]?[\\s+]?(\\d{1,4}|"+MONTH+")[\\s+|\\t|T]?(\\d{0,2}):?(\\d{0,2}):?(\\d{0,2})[.|,]?[\\s]?(\\d{0,3})?([+|-])?(\\d{0,2})[:]?(\\d{0,2})[\\s+]?([A|P]M)?";
DatePattern = Pattern.compile(dateRegEx);
}
private static void initializeMonthName() {
String[] monthName=getMonthString(true);
for(int i=0;i<12;i++){
monthMap.put(monthName[i].toLowerCase(), Integer.valueOf(i+1));
}
monthName=getMonthString(false);
for(int i=0;i<12;i++){
monthMap.put(monthName[i].toLowerCase(), Integer.valueOf(i+1));
}
Iterator<String> it = monthMap.keySet().iterator();
while(it.hasNext()){
String month=it.next();
if(MONTH.isEmpty()){
MONTH=month;
}else{
MONTH=MONTH + "|" + month;
}
}
}
public static boolean isInteger(Object object) {
if(object instanceof Integer) {
return true;
} else {
try{
Integer.parseInt(object.toString());
}catch(Exception e) {
return false;
}
}
return true;
}
public static String[] getMonthString(boolean isShort) {
DateFormatSymbols dfs = new DateFormatSymbols();
if (isShort) {
return dfs.getShortMonths();
} else {
return dfs.getMonths();
}
}
public static int getMonthMap(String value) {
if(monthMap.get(value)==null){
return 0;
}
return monthMap.get(value).intValue();
}
public static long parseDate(String value){
Matcher matcher = DatePattern.matcher(value);
int Year=0, Month=0, Day=0;
boolean isYearFound=false;
boolean isMonthFound=false;
boolean isDayFound=false;
if(matcher.find()) {
for(int i=1;i<matcher.groupCount();i++){
String data=matcher.group(i)==null?"":matcher.group(i);
if(data.equalsIgnoreCase("null")){
data="";
}
//System.out.println(String.valueOf(i) + ": " + data);
switch(i){
case 1:
if(!data.isEmpty()){
if(isInteger(data)){
Integer YMD = Integer.valueOf(data);
if(YMD==0){
return 0;
}
if(YMD>31){
Year = YMD.intValue();
isYearFound = true;
}else if(YMD>12){
Day = YMD.intValue();
isDayFound = true;
}else {
Month=YMD.intValue();
isMonthFound=true;
}
}else {
Month = getMonthMap(data.toLowerCase());
if(Month==0){
return 0;
}
isMonthFound=true;
}
}else {
return 0;
}
break;
case 2:
if(!data.isEmpty()){
if(isInteger(data)){
Integer YMD = Integer.valueOf(data);
if(YMD==0){
return 0;
}
if(YMD>31){
if(isYearFound) {
return 0;
}
Year = YMD.intValue();
isYearFound = true;
}else if(YMD>12){
if(isDayFound) {
return 0;
}
Day = YMD.intValue();
isDayFound = true;
}else {
if(isMonthFound){
Day=YMD.intValue();
isDayFound=true;
}else{
Month=YMD.intValue();
isMonthFound=true;
}
}
}else {
if(isMonthFound){
Day=Month;
isDayFound=true;
}
Month = getMonthMap(data.toLowerCase());
if(Month==0){
return 0;
}
isMonthFound=true;
}
}else {
return 0;
}
break;
case 3:
if(!data.isEmpty()){
if(isInteger(data)){
Integer YMD = Integer.valueOf(data);
if(YMD==0){
return 0;
}
if(YMD>31){
if(isYearFound) {
return 0;
}
Year = YMD.intValue();
isYearFound = true;
}else if(YMD>12){
if(isDayFound) {
return 0;
}
Day = YMD.intValue();
isDayFound = true;
}else {
if(isMonthFound){
Day=YMD.intValue();
isDayFound=true;
}else {
Month = YMD.intValue();
isMonthFound=true;
}
}
}else {
if(isMonthFound){
Day=Month;
isDayFound=true;
}
Month = getMonthMap(data.toLowerCase());
if(Month==0){
return 0;
}
isMonthFound=true;
}
}else {
return 0;
}
break;
case 4:
//hour
break;
case 5:
//minutes
break;
case 6:
//second
break;
case 7:
//millisecond
break;
case 8:
//time zone +/-
break;
case 9:
//time zone hour
break;
case 10:
// time zone minute
break;
case 11:
//AM/PM
break;
}
}
}
Calendar c = Calendar.getInstance();
c.set(Year, Month-1, Day, 0, 0);
return c.getTime().getTime();
}
public static void main(String[] argv) throws IOException {
long d= DateUtils.parseDate("16 July 2012");
Date dt = new Date(d);
SimpleDateFormat df2 = new SimpleDateFormat("d MMMM yyyy");
String dateText = df2.format(dt);
System.out.println(dateText);
d= DateUtils.parseDate("March 20 2012");
dt = new Date(d);
dateText = df2.format(dt);
System.out.println(dateText);
d= DateUtils.parseDate("2012 March 20");
dt = new Date(d);
dateText = df2.format(dt);
System.out.println(dateText);
}
}
public static String detectDateFormat(Context context, String inputDate, String requiredFormat) {
String tempDate = inputDate.replace("/", "").replace("-", "").replace(" ", "");
String dateFormat = "";
if (tempDate.matches("([0-12]{2})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMddyyyy";
} else if (tempDate.matches("([0-31]{2})([0-12]{2})([0-9]{4})")) {
dateFormat = "ddMMyyyy";
} else if (tempDate.matches("([0-9]{4})([0-12]{2})([0-31]{2})")) {
dateFormat = "yyyyMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([0-12]{2})")) {
dateFormat = "yyyyddMM";
} else if (tempDate.matches("([0-31]{2})([a-z]{3})([0-9]{4})")) {
dateFormat = "ddMMMyyyy";
} else if (tempDate.matches("([a-z]{3})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMMddyyyy";
} else if (tempDate.matches("([0-9]{4})([a-z]{3})([0-31]{2})")) {
dateFormat = "yyyyMMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([a-z]{3})")) {
dateFormat = "yyyyddMMM";
} else {
}
try {
String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));
Toast.makeText(context, formattedDate, Toast.LENGTH_SHORT).show();
return formattedDate;
} catch (Exception e) {
Toast.makeText(context, "Please check the date format", Toast.LENGTH_SHORT).show();
return "";
}
}
I encountered this issue as well, where at some places:
I did the same thing having a collection of format which matches my need.
Updated my sql query in a way that it returns the date in a format which I can easily parse for e.g. used this in my query TO_CHAR (o.CREATE_TS, 'MM-DD-YYYY')
& while converting in my other desired format used "MM-dd-yyyy" in java to parse and change to desired format.
Hopefully, #2 will help you in atleast few cases.
hi all how to generate dates if the start date and end date are provided in java?
like the following :
Ex : if the start date is 15-04-2012 and end date is 15-06-2012 having this i want dates to be like the following and the list should omit saturday and sunday
1.15-04-2012,
2.16-04-2012,
3.17-04-2012,
.
.
.
.
.
.
15-06-2012
I have done like the following but it will generate for one month if the date range is of same month.
`
public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, int month, int day){
int totalworkingdays=0,noofdays=0;
String nameofday = "";
ConcurrentHashMap<String,String> workingDaysMap = new ConcurrentHashMap<String,String>();
Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
noofdays = findNoOfDays(year,month,day);
for (int i = 1; i <= noofdays; i++) {
Date date = (new GregorianCalendar(year,month - 1, i)).getTime(); // year,month,day
SimpleDateFormat f = new SimpleDateFormat("EEEE");
nameofday = f.format(date);
String daystr="";
String monthstr="";
if(i<10)daystr="0";
if(month<10)monthstr="0";
String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;
if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
workingDaysMap.put(formatedDate,formatedDate);
totalworkingdays++;
}
}
return workingDaysMap;
}
So please do advice me how to go about.
Regards
Tony
int noOfDaysBetween = 5;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
for(int index = 0 ; index < noOfDaysBetween; index++){
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if( dayOfWeek!=Calendar.SUNDAY && dayOfWeek!=Calendar.SATURDAY) {
System.out.println(cal.getTime());
}
cal.add(Calendar.DATE, 1);
}
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
//15-04-2012
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, 3);
Date start = calendar.getTime();
//15-06-2012
calendar.set(Calendar.MONTH, 5);
Date end = calendar.getTime();
calendar.setTime(start);
Date d = null;
while((d = calendar.getTime()).before(end) || d.equals(end)) {
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day != Calendar.SATURDAY && day != Calendar.SUNDAY) {
System.out.println(d);
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
I prefer usage of LocalDate.
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Game {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2018, 6, 1);
LocalDate end = LocalDate.of(2018, 8, 1);
LocalDate d = start;
while(d.compareTo(end) <= 0) {
if (d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY) {
System.out.println(d);
}
d = d.plusDays(1);
}
}
}
use the following joda-time
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DatesexcludingWeekend {
public static void main(String[] args) {
final LocalDate start = new LocalDate(2012, 06, 15);
final LocalDate end = new LocalDate(2012, 07, 14);
LocalDate weekday = start;
if (start.getDayOfWeek() == DateTimeConstants.SATURDAY|| start.getDayOfWeek() == DateTimeConstants.SUNDAY) {
weekday = weekday.plusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY);
}
while (weekday.isBefore(end)) {
System.out.println(weekday);
if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
weekday = weekday.plusDays(3);
else
weekday = weekday.plusDays(1);
}
}
I am trying to get this to output all the weekdays (MON-FRI) between 5/16/2010 (a sunday) and 5/25/2010 (a tuesday). The correct output should be 17,18,19,20,21,24,25. However, the result im getting is 17,18,19,20,21,17,18,19. The other methods just split up the string the date is in
import java.util.*;
public class test
{
public static void main(String[] args) {
String startTime = "5/16/2010 11:44 AM";
String endTime = "5/25/2010 12:00 PM";
GregorianCalendar startCal = new GregorianCalendar();
startCal.setLenient(true);
String[] start = splitString(startTime);
//this sets year, month day
startCal.set(Integer.parseInt(start[2]),Integer.parseInt(start[0])-1,Integer.parseInt(start[1]));
startCal.set(GregorianCalendar.HOUR, Integer.parseInt(start[3]));
startCal.set(GregorianCalendar.MINUTE, Integer.parseInt(start[4]));
if (start[5].equalsIgnoreCase("AM")) { startCal.set(GregorianCalendar.AM_PM, 0); }
else { startCal.set(GregorianCalendar.AM_PM, 1); }
GregorianCalendar endCal = new GregorianCalendar();
endCal.setLenient(true);
String[] end = splitString(endTime);
endCal.set(Integer.parseInt(end[2]),Integer.parseInt(end[0])-1,Integer.parseInt(end[1]));
endCal.set(GregorianCalendar.HOUR, Integer.parseInt(end[3]));
endCal.set(GregorianCalendar.MINUTE, Integer.parseInt(end[4]));
if (end[5].equalsIgnoreCase("AM")) { endCal.set(GregorianCalendar.AM_PM, 0); }
else { endCal.set(GregorianCalendar.AM_PM, 1); }
for (int i = startCal.get(Calendar.DATE); i < endCal.get(Calendar.DATE); i++)
{
startCal.set(Calendar.DATE, i);
startCal.set(Calendar.DAY_OF_WEEK, i);
if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
{
System.out.println("\t" + startCal.get(Calendar.DATE));
}
}
}
private static String[] splitDate(String date)
{
String[] temp1 = date.split(" "); // split by space
String[] temp2 = temp1[0].split("/"); // split by /
//5/21/2010 10:00 AM
return temp2; // return 5 21 2010 in one array
}
private static String[] splitTime(String date)
{
String[] temp1 = date.split(" "); // split by space
String[] temp2 = temp1[1].split(":"); // split by :
//5/21/2010 10:00 AM
String[] temp3 = {temp2[0], temp2[1], temp1[2]};
return temp3; // return 10 00 AM in one array
}
private static String[] splitString(String date)
{
String[] temp1 = splitDate(date);
String[] temp2 = splitTime(date);
String[] temp3 = new String[6];
return dateFill(temp3, temp2[0], temp2[1], temp2[2], temp1[0], temp1[1], temp1[2]);
}
private static String[] dateFill(String[] date, String hours, String minutes, String ampm, String month, String day, String year) {
date[0] = month;
date[1] = day;
date[2] = year;
date[3] = hours;
date[4] = minutes;
date[5] = ampm;
return date;
}
private String dateString(String[] date) {
//return month+" "+day+", "+year+" "+hours+":"+minutes+" "+ampm
//5/21/2010 10:00 AM
return date[3]+"/"+date[4]+"/ "+date[5]+" "+date[0]+":"+date[1]+" "+date[2];
}
}
startCal.set(Calendar.DAY_OF_WEEK, i); Will flip flip your date back every 7 loops.
This code isn't good.
I don't understand why you're doing all this parsing of Strings to get to Date and visa versa when you have java.text.DateFormat and java.text.SimpleDateFormat to do it easily for you.
I think this is better. See if you agree:
package com.contacts.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtils
{
private static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("dd-MMM-yyyy");
public static void main(String[] args)
{
try
{
Date startDate = ((args.length > 0) ? DEFAULT_FORMAT.parse(args[0]) : new Date());
Date endDate = ((args.length > 1) ? DEFAULT_FORMAT.parse(args[1]) : new Date());
List<Date> weekdays = DateUtils.getWeekdays(startDate, endDate);
Calendar calendar = Calendar.getInstance();
for (Date d : weekdays)
{
calendar.setTime(d);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
// System.out.println(DEFAULT_FORMAT.format(d));
System.out.println("day: " + dayOfMonth + " month: " + (month+1) + " year: " + year);
}
}
catch (ParseException e)
{
e.printStackTrace();
}
}
public static List<Date> getWeekdays(Date startDate, Date endDate)
{
List<Date> weekdays = new ArrayList<Date>();
if ((startDate == null) || (endDate == null))
return weekdays;
if (startDate.equals(endDate))
{
if (isWeekday(startDate))
{
weekdays.add(startDate);
}
}
else if (startDate.after(endDate))
{
weekdays = getWeekdays(endDate, startDate);
}
else
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
Date d = startDate;
while (endDate.equals(d) || endDate.after(d))
{
if (isWeekday(d))
{
weekdays.add(d);
}
calendar.add(Calendar.DATE, 1);
d = calendar.getTime();
}
}
return weekdays;
}
public static boolean isWeekday(Date d)
{
if (d == null)
return false;
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
return ((dayOfWeek >= Calendar.MONDAY) && (dayOfWeek <= Calendar.FRIDAY));
}
}
I don't know if this is an issue with your code, but JDK uses some unexpected values for Calendar constants. For example, months star with zero. In other words, Calendar.JANUARY is 0. On the other hand, weekdays are 1 to 7, starting with Sunday as 1. etc.
I luckily don't know much about Date in Java, but I know it's basically a difficult and bad API. Go for JodaTime until the new JSR-310 is done.