I get wrong output in ICU4J library - java

I want to convert date from Persian calendar to Gregorian Calendar.
For this, I use ICU4J library (version 65.1).
The problem is that this library gives wrong output for some dates.
Here is my code:
ULocale locale = new ULocale("fa_IR#calendar=persian");
GregorianCalendar gregoriancal = new GregorianCalendar();
Calendar persiancal = Calendar.getInstance(locale);
// year month day
persiancal.set(1398, 11, 16);
gregoriancal.setTime(persiancal.getTime());
String day = gregoriancal.get(Calendar.DATE) + "";
System.out.println(day);
----------------------------------------
output: 6
this date in persian calendar ( 1398/11/16 ) equls to 2020-02-05 Wednesday February in Gregorian Calendar
but it gives me 6 as output ( while it should give 5 )
is there something wrong with my code that results in a wrong output??

After looking at the javadoc passing the ULocale should do the trick to put the GregorianCalendar in the correct time zone:
com.ibm.icu.util.GregorianCalendar gregoriancal =
new com.ibm.icu.util.GregorianCalendar(locale);
I think the month may be 0-based as in java.util.Calendar.
persiancal.set(1398, 11-1, 16);

Related

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

How to reduce one month from current date and stored in date variable using java?

How to reduce one month from current date and want to sore in java.util.Date variable
im using this code but it's shows error in 2nd line
java.util.Date da = new Date();
da.add(Calendar.MONTH, -1); //error
How to store this date in java.util.Date variable?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date result = cal.getTime();
Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar.
If you want a Date object to be returned:
Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());
If you don't need exactly a Date object, you can use the classes directly, provided by the package, even to get dates in other time-zones:
ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
Calendar calNow = Calendar.getInstance()
// adding -1 month
calNow.add(Calendar.MONTH, -1);
// fetching updated time
Date dateBeforeAMonth = calNow.getTime();
you can use Calendar
java.util.Date da = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(da);
cal.add(Calendar.MONTH, -1);
da = cal.getTime();
Using new java.time package in Java8 and Java9
import java.time.LocalDate;
LocalDate mydate = LocalDate.now(); // Or whatever you want
mydate = mydate.minusMonths(1);
The advantage to using this method is that you avoid all the issues about varying month lengths and have more flexibility in adjusting dates and ranges. The Local part also is Timezone smart so it's easy to convert between them.
As an aside, using java.time you can also get the day of the week, day of the month, all days up to the last of the month, all days up to a certain day of the week, etc.
mydate.plusMonths(1);
mydate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).getDayOfMonth();
mydate.with(TemporalAdjusters.lastDayOfMonth());
Using JodaTime :
Date date = new DateTime().minusMonths(1).toDate();
JodaTime provides a convenient API for date manipulation.
Note that similar Date API will be introduced in JDK8 with the JSR310.
You can also use the DateUtils from apache common. The library also supports adding Hour, Minute, etc.
Date date = DateUtils.addMonths(new Date(), -1)
raduce 1 month of JDF
Date dateTo = new SimpleDateFormat("yyyy/MM/dd").parse(jdfMeTo.getJulianDate());
Calendar cal = Calendar.getInstance();
cal.setTime(dateTo);
cal.add(Calendar.MONTH, -1);
Date dateOf = cal.getTime();
Log.i("dateOf", dateOf.getTime() + "");
jdfMeOf.setJulianDate(cal.get(Calendar.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));

Java Date/Calendar oddness

I have a bit of (Java) that I where I am trying to simply subtract 7 days from the current date. It seemed to me like Calendar.add(..) should be the method to use (and what previous questions here seem to say), so that's what I tried:
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
System.out.println("ReportUtil.getDefaultReportStartDate cal: "+cal.toString() );
System.out.println("PRE ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
cal.add(Calendar.DATE, -7);
System.out.println("POST ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
That looks ok to me but you'll see from the output below the month field seems to go a bit... sideways! The day of the month/date seems to change correctly, but what is going on with the month?!
ReportUtil.getDefaultReportStartDate cal: java.util.GregorianCalendar[time=1330098699960,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GB-Eire",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=GB-Eire,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2012,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=55,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=51,SECOND=39,MILLISECOND=960,ZONE_OFFSET=0,DST_OFFSET=0]
PRE ReportUtil.getDefaultReportStartDate: 24-51-2012
POST ReportUtil.getDefaultReportStartDate: 17-51-2012
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
You get a strange month value because mm means minutes. Try:
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
You can consult the whole list of the format symbols here: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
mm is the format string for Minute. You want MM
Your result seems to be correct.
The month is "1" in both dates of your first log line, which means February.
The "-mm-" in your SimpleDateFormat means minute and not month, thus the odd month of "51"

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

Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows:
2011-10
The week value is the week of the year(so 1-52). From this week value, I need to output something like the following:
Mar 7
Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. So in other words it is saying that the 10th week of the year is the week of March 7th.
I am using Groovy. What kind of date manipulation can I do to get this to work?
Here's a groovy solution:
use(groovy.time.TimeCategory) {
def (y, w) = "2011-10".tokenize("-")
w = ((w as int) + 1) as String
def d = Date.parse("yyyy-w", "$y-$w") + 1.day
println d.format("MMM dd")
}
Use a GregorianCalendar (or Joda, if you don't mind a dependency)
String date = "2011-10";
String[] parts = date.split("-");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
DateFormat df = new SimpleDateFormat("MMM d");
System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");
EDIT: Added +1 to week, since calendar uses zero-based week numbers
Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));
The first line returns first day of the 10th week in British Locale (March 7th). When Locale is not enforced, the results are dependent on default JVM Locale.
Formats are explained here.
You can use SimpleDateFormat, just like in java. See groovyconsole.appspot.com/script/439001
java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')
To add a week, simply use Date date = df.parse('2011-10')+7
You don't need to set the Locale if your default Locale is using Monday as the first day of week.

Categories