how to find the day in the month in java? - java

this is what i do to get date in java :
Date date = (new GregorianCalendar(year,month - 1, i)).getTime(); // year,month,day
SimpleDateFormat f = new SimpleDateFormat("EEEE");
nameofday = f.format(date);
when i print the date Object it gives me the answer like follows :
Sun Apr 01 00:00:00 IST 2012
Mon Apr 02 00:00:00 IST 2012
Tue Apr 03 00:00:00 IST 2012
Wed Apr 04 00:00:00 IST 2012
Thu Apr 05 00:00:00 IST 2012
Fri Apr 06 00:00:00 IST 2012
Sat Apr 07 00:00:00 IST 2012
from this i want to get only the day ex: 01,02,03,04,05,etc.
How to do this in java?
Regards
Tony

If you want the day as a number, use:
int dayOfMonth = gregorianCalendarInstance.get(Calendar.DATE);
If you want a string like "05", change your date format to dd, that is:
SimpleDateFormat f = new SimpleDateFormat("dd");

Your output is not the nameofday. If you printed nameofday, it would print "saturday" or "friday". If you want the day in the month on two characters, as indicated in the javadoc of SimpleDateFormat, you must use "dd" for the pattern:
Date date = ...
DateFormat df = new SimpleDateFormat("dd");
System.out.println(df.format(date));
You should really learn to read documentation.

Related

SimpleDateFormat returning the wrong date in Java

I'm having an issue with SimpleDateFormat in Java. My code is returning the wrong date. Help please.
String date_str = "Tue Mar 08 09:44:55 EST 2022";
Date date = new SimpleDateFormat("EEE MMM D HH:mm:ss z yyyy").parse(date_str);
// Output: Sat Jan 08 14:44:55 GMT 2022
d, not D for the day of the month. D is the day in the year, so 8 is the 8 of January.
String date_str = "Tue Mar 08 09:44:55 EST 2022";
Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy").parse(date_str);
// ^---Here
// Output: Tue Mar 08 15:44:55 CET 2022
Check the full list of patterns here.

Java Date - Leap year - strange behavior

So I've got this kind of strange problem with Java's Date.
The entry-point for this problem are 2 String dates startDate("30 Jan 2016") and endate ""29 Jan 2017".
The problem is a little bit more complex,but I've summed it up just to this case.
What I have to do is get an 1 year schedule exactly like the one from bellow starting with this data.
The table contains for each month: first day, last day, and days between those 2 days.
Expected results:
/**
Sat Jan 30 00:00:00 GMT 2016 - Sun Feb 28 23:59:59 GMT 2016 - 30
Mon Feb 29 00:00:00 GMT 2016 - Tue Mar 29 23:59:59 BST 2016 - 30
Wed Mar 30 00:00:00 BST 2016 - Fri Apr 29 23:59:59 BST 2016 - 31
Sat Apr 30 00:00:00 BST 2016 - Sun May 29 23:59:59 BST 2016 - 30
Mon May 30 00:00:00 BST 2016 - Wed Jun 29 23:59:59 BST 2016 - 31
Thu Jun 30 00:00:00 BST 2016 - Fri Jul 29 23:59:59 BST 2016 - 30
Sat Jul 30 00:00:00 BST 2016 - Mon Aug 29 23:59:59 BST 2016 - 31
Tue Aug 30 00:00:00 BST 2016 - Thu Sep 29 23:59:59 BST 2016 - 31
Fri Sep 30 00:00:00 BST 2016 - Sat Oct 29 23:59:59 BST 2016 - 30
Sun Oct 30 00:00:00 BST 2016 - Tue Nov 29 23:59:59 GMT 2016 - 31
Wed Nov 30 00:00:00 GMT 2016 - Thu Dec 29 23:59:59 GMT 2016 - 30
Fri Dec 30 00:00:00 GMT 2016 - Sun Jan 29 23:59:59 GMT 2017 - 31
*/
My results are
Sat Jan 30 00:00:00 EET 2016 ::::: Sun Feb 28 23:59:59 EET 2016 ::::: 29
Mon Feb 29 00:00:00 EET 2016 ::::: Mon Mar 28 23:59:59 EEST 2016 ::::: 28
Tue Mar 29 00:00:00 EEST 2016 ::::: Thu Apr 28 23:59:59 EEST 2016 ::::: 30
Fri Apr 29 00:00:00 EEST 2016 ::::: Sat May 28 23:59:59 EEST 2016 ::::: 29
Sun May 29 00:00:00 EEST 2016 ::::: Tue Jun 28 23:59:59 EEST 2016 ::::: 30
Wed Jun 29 00:00:00 EEST 2016 ::::: Thu Jul 28 23:59:59 EEST 2016 ::::: 29
Fri Jul 29 00:00:00 EEST 2016 ::::: Sun Aug 28 23:59:59 EEST 2016 ::::: 30
Mon Aug 29 00:00:00 EEST 2016 ::::: Wed Sep 28 23:59:59 EEST 2016 ::::: 30
Thu Sep 29 00:00:00 EEST 2016 ::::: Fri Oct 28 23:59:59 EEST 2016 ::::: 29
Sat Oct 29 00:00:00 EEST 2016 ::::: Mon Nov 28 23:59:59 EET 2016 ::::: 31
Tue Nov 29 00:00:00 EET 2016 ::::: Wed Dec 28 23:59:59 EET 2016 ::::: 29
Thu Dec 29 00:00:00 EET 2016 ::::: Sat Jan 28 23:59:59 EET 2017 ::::: 30
So I’m not sure if this happens because of the February month or because 2016 was a leap year that included 29th of February.
What am I missing? I have the same problem run multiple test cases and all others are OK, but this.
I've also tried to do this with Javas 8 LocalDate and LocalDateTime and I get the exactly same results.
Here is my code
import org.apache.commons.lang.time.DateUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) throws ParseException {
String startDate = "30 Jan 2016";
String endDate = "29 Jan 2017"; // current not using this ?!
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
Date start = formatter.parse(startDate);
List<Item> items = new ArrayList<>();
for (int i = 0; i < 12; i++) {
Date end = DateUtils.addMonths(start, 1);
end = DateUtils.addSeconds(end, -1);
items.add(new Item(start, end));
start = DateUtils.addMonths(start, 1);
}
items.forEach(item -> {
System.out.println(item.getStart() + " ::::: " + item.getEnd() + " ::::: " + getDifferenceDays(item.getStart(), item.getEnd()));
});
}
public static long getDifferenceDays(Date d1, Date d2) {
return ChronoUnit.DAYS.between(d1.toInstant(), d2.toInstant());
}
}
Item Class
import java.util.Date;
public class Item {
Date start;
Date end;
public Item(Date start, Date end) {
this.start = start;
this.end = end;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
#Override
public String toString() {
return "Item{" +
"start=" + start +
", end=" + end +
'}';
}
}
java.time
Since you can use java.time, the modern Java date and time API, I recommend that you stick to that and leave the old classes SimpleDateFormat and Date alone. Then you also don’t need the Apache DateUtils. The ChronoUnit enum is from java.time.
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d MMM u", Locale.ENGLISH);
String startDateString = "30 Jan 2016";
LocalDate originalStartDate
= LocalDate.parse(startDateString, dateFormatter);
for (int i = 0; i < 12; i++) {
LocalDate startDate = originalStartDate.plusMonths(i);
LocalDate nextStartDate = originalStartDate.plusMonths(i + 1);
LocalDate endDate = nextStartDate.minusDays(1);
long differenceDays = ChronoUnit.DAYS.between(startDate, nextStartDate);
System.out.format("%s - %s : %d%n", startDate, endDate, differenceDays);
}
Output is:
2016-01-30 - 2016-02-28 : 30
2016-02-29 - 2016-03-29 : 30
2016-03-30 - 2016-04-29 : 31
2016-04-30 - 2016-05-29 : 30
2016-05-30 - 2016-06-29 : 31
2016-06-30 - 2016-07-29 : 30
2016-07-30 - 2016-08-29 : 31
2016-08-30 - 2016-09-29 : 31
2016-09-30 - 2016-10-29 : 30
2016-10-30 - 2016-11-29 : 31
2016-11-30 - 2016-12-29 : 30
2016-12-30 - 2017-01-29 : 31
What went wrong in your code?
There are a couple of reasons behind your observed unexpected results.
When you add a month to January 30, you get February 29 as you had expected. In a non-leap year you would have got February 28. When you add another month to February 29, you get March 29. Is it surprising when you think about it? In a non-leap year you would have got March 28, so 2016 being a leap year actually helped you get closer to your desired result. In my code I solve this problem by adding the correct number of months to the original start date rather than adding one month to the previous start date.
As PeterMmm already said, ChronoUnit.DAYS.Between() counts full 24 hours days. Any partial day is discarded. Even 23 hours 59 minutes 59 seconds. From Sat Jan 30 00:00:00 EET 2016 to Sun Feb 28 23:59:59 EET 2016 is 30 days 23 hours 59 minutes 59 seconds, so the result you get is 30 days. In my code I solve the problem by counting the days until the start of the next item.
As an aside: From Mon Feb 29 00:00:00 EET 2016 to Mon Mar 28 23:59:59 EEST 2016, because of transistion to summer time (DST) is only 28 days 22 hours 59 minutes 59 seconds. So abstaining from subtracting a second would not solve your problem in this case.
This
end = DateUtils.addSeconds(end, -1);
isn't necessary. Or do
end = DateUtils.addSeconds(end, 0);
have a look at between() documentation.
Second parameter is exclusive. That means, your second parameter does not reach the end of day and so a day less is counted (only full 24h days are counted).
Here's a slightly different approach:
LocalDate startDate = LocalDate.of(2016, 1, 30);
LocalDate endDate = LocalDate.of(2017, 1, 30);
Function<YearMonth, LocalDate> addMonthFunction = ym -> ym
.atDay(Math.min(startDate.getDayOfMonth(), ym.lengthOfMonth()));
long months = ChronoUnit.MONTHS.between(startDate, endDate);
YearMonth yearMonth = YearMonth.from(startDate);
Stream.iterate(yearMonth, ym -> ym.plusMonths(1))
.limit(months)
.map(addMonthFunction)
.map(LocalDate::atStartOfDay)
.map(date -> {
LocalDateTime end = addMonthFunction.apply(YearMonth.from(date.plusMonths(1)))
.atStartOfDay()
.minusSeconds(1);
long between = ChronoUnit.DAYS.between(date, end) + 1;
return String.format("%s to %s (%s days)", date, end, between);
})
.forEach(System.out::println);
The idea is that each next date always falls on the 30th day of the month (or, more precisely, the same day-of-month as the start date), except if that would be an invalid date.
I used LocalDates here, but you could make it timezone-sensitive by using ZonedDateTime.

Increment and print all days in a month

I have started writing some code and need to print all the dates in a month, I can do this by adding one each day but there must be a shorter way that I am missing. This is my code so far.
I am aware that it is not the prettiest and I am wondering how to print the date while it increments for each day in January without having to constantly add 1 each time then println each time.
public static void main(String [] args) {
Calendar calendar = Calendar.getInstance()
calendar.set.(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]));
System.out.println(calendar.getTime());
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.getTime());
}
}
simple exmple using Java 8 Local date, asuming input as in the question
import java.time.LocalDate;
public class Test
{
public static void main(String[] args)
{
LocalDate ld = LocalDate.of(Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]));
do {
System.out.println(ld.toString());
ld = ld.plusDays(1);
} while (ld.getDayOfMonth() > 1); // arive at 1st of next month
}
}
Here's a simple example that prints all the days in the month. The time parts have been set to zero.
Here, we printed all the days in March 2016.
Tue Mar 01 00:00:00 MST 2016
Wed Mar 02 00:00:00 MST 2016
Thu Mar 03 00:00:00 MST 2016
Fri Mar 04 00:00:00 MST 2016
Sat Mar 05 00:00:00 MST 2016
Sun Mar 06 00:00:00 MST 2016
Mon Mar 07 00:00:00 MST 2016
Tue Mar 08 00:00:00 MST 2016
Wed Mar 09 00:00:00 MST 2016
Thu Mar 10 00:00:00 MST 2016
Fri Mar 11 00:00:00 MST 2016
Sat Mar 12 00:00:00 MST 2016
Sun Mar 13 00:00:00 MST 2016
Mon Mar 14 00:00:00 MDT 2016
Tue Mar 15 00:00:00 MDT 2016
Wed Mar 16 00:00:00 MDT 2016
Thu Mar 17 00:00:00 MDT 2016
Fri Mar 18 00:00:00 MDT 2016
Sat Mar 19 00:00:00 MDT 2016
Sun Mar 20 00:00:00 MDT 2016
Mon Mar 21 00:00:00 MDT 2016
Tue Mar 22 00:00:00 MDT 2016
Wed Mar 23 00:00:00 MDT 2016
Thu Mar 24 00:00:00 MDT 2016
Fri Mar 25 00:00:00 MDT 2016
Sat Mar 26 00:00:00 MDT 2016
Sun Mar 27 00:00:00 MDT 2016
Mon Mar 28 00:00:00 MDT 2016
Tue Mar 29 00:00:00 MDT 2016
Wed Mar 30 00:00:00 MDT 2016
Thu Mar 31 00:00:00 MDT 2016
This code will work with Java 6, Java 7, and Java 8.
package com.ggl.testing;
import java.util.Calendar;
public class PrintMonth {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
if (args.length == 2) {
int year = Integer.parseInt(args[0]);
int month = Integer.parseInt(args[1]);
calendar.set(year, month, 1);
}
int month = calendar.get(Calendar.MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
while (calendar.get(Calendar.MONTH) == month) {
System.out.println(calendar.getTime());
calendar.add(Calendar.DATE, 1);
}
}
}
public static void main(String[] args) {
LocalDate date = LocalDate.of(Integer.parseInt(args[0]), Integer.parseInt(args[1]), 1);
for (int i = 0; i < date.lengthOfMonth(); i++) {
System.out.println(date);
date = date.plusDays(1);
}
}
This is a working example:
https://github.com/OpenGamma/OG-Platform/blob/master/projects/OG-Util/src/main/java/com/opengamma/util/time/LocalDateRange.java#L113
public static LocalDateRange of(LocalDate startDateInclusive, LocalDate endDate, boolean endDateInclusive) {
ArgumentChecker.notNull(startDateInclusive, "startDate");
ArgumentChecker.notNull(endDate, "endDate");
if (endDateInclusive == false && endDate.isBefore(LocalDate.MAX)) {
endDate = endDate.minusDays(1);
}
if (endDate.isBefore(startDateInclusive)) {
throw new IllegalArgumentException("Start date must be on or after end date");
}
return new LocalDateRange(startDateInclusive, endDate);
}
How about this example?:
#JRubyMethod(name = {"asctime", "ctime"})
public RubyString asctime() {
DateTimeFormatter simpleDateFormat;
if (dt.getDayOfMonth() < 10) {
simpleDateFormat = ONE_DAY_CTIME_FORMATTER;
} else {
simpleDateFormat = TWO_DAY_CTIME_FORMATTER;
}
String result = simpleDateFormat.print(dt);
return getRuntime().newString(result);
}
Full source here: http://code.openhub.net/file?fid=VJqxO5av-KgtoQFAp9juIzamnTc&cid=KOJoiAJBzj4&s=Increment%20and%20print%20all%20days%20in%20a%20month&pp=0&fl=Java&ff=1&filterChecked=true&fp=144796&mp,=1&ml=0&me=1&md=1&projSelected=true#L0

DateUtils.addDays() class issue in daylight saving time

Recently New Zealand observed daylight saving on 27 sept 15.
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
sd.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland"));
Date dateValue = sd.parse("2015-09-30");
System.out.println(dateValue); // prints "Tue Sep 29 07:00:00 EDT 2015" My local system timzone in EDT
dateValue = DateUtils.addDays(dateValue, -6); // 6 days back 24 Sep of Pacific/Auckland
System.out.println(dateValue); // prints "Tue Sep 23 07:00:00 EDT 2015"
The second print statement should print Tue Sep 29 08:00:00 EDT 2015, as Daylight Saving not is in effect.
The issue is before 27 Sep 15 NZ = UTC+12
and after NZ = UTC +13
So on date of 23 Sep It should have time 08:00:00 not 07:00:00
The problem is within DateUtils.addDays from Apache Commons: it is using a Calendar with the default timezone to add and subtract days instead of using a user-supplied timezone. You can see this in the source code of the method add: it calls Calendar.getInstance() and not Calendar.getInstance(someTimezone)
If you construct yourself the Calendar and set the correct timezone, the problem disappears:
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
sd.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland"));
Date dateValue = sd.parse("2015-09-30");
System.out.println(dateValue); // prints "Tue Sep 29 13:00:00 CEST 2015"
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Pacific/Auckland")); // set correct timezone to calendar
calendar.setTime(dateValue);
calendar.add(Calendar.DAY_OF_MONTH, -6);
dateValue = calendar.getTime();
System.out.println(dateValue); // prints "Wed Sep 23 14:00:00 CEST 2015"
also i have used joda api to resolved this timezone issue.
org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "Pacific/Auckland" );
DateTime currentDate= new DateTime( new Date(), timeZone );
DateTime dateValue = now.plusDays( -6 ); // prints Tue Sep 29 08:00:00 EDT 2015

Simple Date Format parsed then formatted date didn't match

I've run into a strange behavior of SimpleDateFormat, i don't know how to deal with.
I need to parse a date in a specific format (Day of Week, then day, then Month, then Year, Then time).
However, I've run into a behaviour, when parsing a date gives me a very strnge result (other date). Here is a small, self-contained example, and it's output on my machine.
public static void main(String[] args) throws Exception {
test("E YYYY kk:mm:ss");
test("E d YYYY kk:mm:ss");
test("E d MMMM YYYY kk:mm:ss");
}
public static void test(String format) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date now = new Date();
System.out.println(now);
String formattedNow = sdf.format(now);
System.out.println(formattedNow);
Date parsedFormattedNow = sdf.parse(formattedNow);
String formattedParsedNow = sdf.format(parsedFormattedNow);
System.out.println(formattedParsedNow);
System.out.println(formattedNow.equals(formattedParsedNow));
}
Output:
Sat Apr 27 13:48:07 MSK 2013
Sat 2013 13:48:07
Sat 2013 13:48:07
true
Sat Apr 27 13:48:07 MSK 2013
Sat 27 2013 13:48:07
Sat 5 2013 13:48:07
false
Sat Apr 27 13:48:07 MSK 2013
Sat 27 April 2013 13:48:07
Sat 5 January 2013 13:48:07
false
Why do then 27 transforms into 5, and April to January?
Well, there are two aspects here:
The pattern E d YYYY kk:mm:ss doesn't contain a month indicator at all. So after formatting to "Sat 27 2013 13:48:07" how are you expecting the parsing part to work out the month?
All your patterns use YYYY which is the week-year, not calendar year. This should usually be used with "day of week, week of week-year" patterns. If you use yyyy instead, the final pattern will work.
The only reason the first pattern appears to work is that you're not actually setting anything other than the "day of week" and the year (and time, of course). If you print out parsedFormattedNow (with no other formatting) you'll see that the parse result is actually January 5th. It's just you don't notice it, because it's still a Saturday.

Categories