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.
Related
I am using the javax.mail classes in order to connect to microsoft outlook and fetch mails.
What I would like to do is to find all of the messages that were sent between 2 dates.
I have the min and max dates as dates of type ZonedDateTime. For example:
ZonedDateTime minZonedDateTime = ZonedDateTime.of(2017, 6, 15, 0, 0, 0, 0, ZoneId.systemDefault());
ZonedDateTime maxZonedDateTime = ZonedDateTime.of(2017, 6, 20, 0, 0, 0, 0, ZoneId.systemDefault());
My default time zone is 'Australia/Sydney'. So in order to fetch all of the mails between those 2 dates I do the following:
Date minDate = Date.from(minZonedDateTime.toInstant());
Date maxDate = Date.from(maxZonedDateTime.toInstant());
SentDateTerm minSentDateTerm = new SentDateTerm(ComparisonTerm.GE, minDate);
SentDateTerm maxSentDateTerm = new SentDateTerm(ComparisonTerm.LE, maxDate);
SearchTerm term = new AndTerm(maxSentDateTerm,minSentDateTerm);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
Message[] messages = folderInbox.search(term);
Now, when I print the sentDates of all of the recieved messages I have the following result:
Tue Jun 20 19:01:57 AEST 2017
Mon Jun 19 18:31:31 AEST 2017
Sun Jun 18 18:54:26 AEST 2017
Sun Jun 18 18:31:24 AEST 2017
Sun Jun 18 01:08:46 AEST 2017
Sat Jun 17 00:54:27 AEST 2017
Fri Jun 16 00:27:56 AEST 2017
All of the messages are correctly fetched and belong to the interval except for the first message that has sentDate value of (Tue Jun 20 19:01:57 AEST 2017)
The sentDate of that message if bigger than the value of maxDate, which is proven by the result of messages[0].getSentDate().compareTo(maxDate) which is 1. How is this possible?
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
I am encountering with a scenario like this.
My project receives a download request from perl
void downloadRequest(FileItemIterator items,
HttpServletResponse response) throws Exception
{
log.info("Start downloadRequest.......");
OutputStream os = response.getOutputStream();
File file = new File("D:\\clip.mp4");
FileInputStream fileIn = new FileInputStream(file);
//while ((datablock = dataOutputStreamServiceImpl.readBlock()) != null)
byte[] outputByte = new byte[ONE_MEGABYE];
while (fileIn.read(outputByte) != -1)
{
System.out.println("--------" + (i = i + 1) + "--------");
System.out.println(new Date());
//dataContent = datablock.getContent();
System.out.println("Start write " + new Date());
os.write(outputByte);
System.out.println("End write " + new Date());
//System.out.println("----------------------");
}
os.close();
}
}
I try to read and write blocks of 1MB from the file. However, it takes too long for downloading the whole file. ( my case is 20mins for file of 100MB)
I try to sysout and I saw a result like this:
The first few blocks can read, write data realy fast:
--------1--------
Mon Dec 07 16:24:20 ICT 2015
Start write Mon Dec 07 16:24:20 ICT 2015
End write Mon Dec 07 16:24:21 ICT 2015
--------2--------
Mon Dec 07 16:24:21 ICT 2015
Start write Mon Dec 07 16:24:21 ICT 2015
End write Mon Dec 07 16:24:21 ICT 2015
--------3--------
Mon Dec 07 16:24:21 ICT 2015
Start write Mon Dec 07 16:24:21 ICT 2015
End write Mon Dec 07 16:24:21 ICT 2015
But the next block is slower than the previous
--------72--------
Mon Dec 07 16:29:22 ICT 2015
Start write Mon Dec 07 16:29:22 ICT 2015
End write Mon Dec 07 16:29:29 ICT 2015
--------73--------
Mon Dec 07 16:29:29 ICT 2015
Start write Mon Dec 07 16:29:29 ICT 2015
End write Mon Dec 07 16:29:37 ICT 2015
--------124--------
Mon Dec 07 16:38:22 ICT 2015
Start write Mon Dec 07 16:38:22 ICT 2015
End write Mon Dec 07 16:38:35 ICT 2015
--------125--------
Mon Dec 07 16:38:35 ICT 2015
Start write Mon Dec 07 16:38:35 ICT 2015
End write Mon Dec 07 16:38:48 ICT 2015
I realy cannot understand how the outputStream write, why it take such a long time like that? or I made some mistakes?
Sorry for my bad english. I realy need your support. Thank in advance!
There is no guaranty that the read(byte[] b) method will read b.length number of bytes from the file which mean that your code could be sending more bytes then the file actually has.
For example, if you're processing a 10 MB file and the read(byte[] b) always reads b.length/2 from the file, you will be sending 20 MB.
To address that, you could do something like this.
byte[] outputByte = new byte[ONE_MEGABYE];
int r = -1;
while ((r = fileIn.read(outputByte)) != -1){
os.write(outputByte,0,r);
}
This will ensure that you'll be sending only as much bytes as there were read from the file.
Beside this issue, the speed can be influenced by a lot of other factors like the internet speed or the other program's implementation.
I got a really annoying problem with calendar class. I have two JTextFields to enter a period of date (txtStart & txtEnd). If start date begins at the first day of month (01.), I set the end date to "last day of month".
Now the user can change change the period by clicking a plus or minus button, then I want to increase or decrease only the month of start & end date.
Calendar tempStart = Calendar.getInstance();
Calendar tempEnd = Calendar.getInstance();
if (txtStart.getText().trim().startsWith("01.")) {
System.out.println("get dates typed by user, and set \"last day of month\" to txtEnd");
tempStart = convStringToDate(txtStart.getText().trim(), false);
System.out.println(tempStart.getTime() + " #+#+###++ ");
tempEnd = getLastDayOfMonth(txtStart.getText().trim());
System.out.println(tempEnd.getTime() + " #+#+###++ ");
System.out.println(" ");
System.out.println("multi is either +1 or -1, increasing or decreasing only the month !");
tempStart.set(Calendar.MONTH, tempStart.get(Calendar.MONTH) + multi);
System.out.println(tempStart.getTime() + " #+#+###++ ");
tempEnd.set(Calendar.MONTH, tempEnd.get(Calendar.MONTH) + multi);
System.out.println(tempEnd.getTime() + " #+#+###++ ");
System.out.println(" ");
}
My methods are working correctly. Now I got some bewildering output.
If I enter 01.11.2015 at txtStart (dd.MM.yyy) I got following output:
get dates typed by user, and set "last day of month" to txtEnd
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Mon Nov 30 23:59:59 GMT 2015 #+#+###++
multi is either +1 or -1, increasing or decreasing only the month !
Tue Dec 01 00:00:01 GMT 2015 #+#+###++
Wed Dec 30 23:59:59 GMT 2015 #+#+###++
Looks pretty nice and everthing seems to work correctly, but if I enter 01.10.2015 at txtStart (dd.MM.yyy) I got following output:
get dates typed by user, and set "last day of month" to txtEnd
Thu Oct 01 00:00:01 GMT 2015 #+#+###++
Sat Oct 31 23:59:59 GMT 2015 #+#+###++
multi is either +1 or -1, increasing or decreasing only the month !
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Tue Dec 01 23:59:59 GMT 2015 #+#+###++
May anyone have an idea why my end date is wrong at output 2.
EDIT:
multi = +1 or -1 (see in output1 or output2 comment)
private Calendar getLastDayOfMonth(String sDate) {
Calendar cal = convStringToDate(sDate, true);
// passing month-1 because 0-->jan, 1-->feb... 11-->dec
// calendar.set(year, month - 1, 1);
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
cal.set(Calendar.HOUR_OF_DAY, MAX_ZEIT[0]); // 23
cal.set(Calendar.MINUTE, MAX_ZEIT[1]); // 59
cal.set(Calendar.SECOND, MAX_ZEIT[2]); // 59
cal.set(Calendar.MILLISECOND, MAX_ZEIT[3]); // 0
// Time: 23:59:59:0
return cal;
}
############## SOLUTION: ####################.
if (txtStart.getText().trim().startsWith("01.")) {
tempStart = convStringToDate(txtStart.getText().trim(), false);
tempEnd = (Calendar) tempStart.clone(); // set the date somewhere at the same month ( e.g. at start date )
tempStart.set(Calendar.MONTH, tempStart.get(Calendar.MONTH) + multi); // inc- or decrease the month first
tempEnd.set(Calendar.MONTH, tempEnd.get(Calendar.MONTH) + multi); // inc- or decrease the month first ( now there is no overflow due to the 30th or 31th day )
tempEnd = getLastDayOfMonth(df2.format(tempEnd.getTime())); // finally setting the "last day of month"
}
The solution is to do first of all to increase or decrease the month, after that I can set the last day of month without getting any overflow problems.
Output:
get dates typed by user, and set "last day of month" to txtEnd
Thu Oct 01 00:00:01 GMT 2015 #+#+###++
Thu Oct 01 00:00:01 GMT 2015 #+#+###++
multi is either +1 or -1, increasing or decreasing only the month !
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
FINALLY
Sun Nov 01 00:00:01 GMT 2015 #+#+###++
Mon Nov 30 23:59:59 GMT 2015 #+#+###++
I thank you all for your help !!!
The end date is incorrect in the first example, as well. It shows 30/12 whereas the last day of December is the 31st. When you add +1 to the month you don't check whether the following month has the same number of days.
November has 30 days. Therefore, incrementing October 31st gives November "31st" which is actually December 1st.
Lots of programmers need to do arithmetic on dates. That's why java.util.Calendar class has a method add() that you can use that encapsulates all the calculations you need. Check the JavaDocs: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int,%20int)
After you have incremented or decremented the month of the start date, use
int lastDayOfMonth = startDate.getActualMaximum(Calendar.DAY_OF_MONTH);
and use startDate in combination with day-of-month set to this value as the endDate.
Calendar sd = new GregorianCalendar( 2015, 1, 1 );
int last = sd.getActualMaximum(Calendar.DAY_OF_MONTH);
Calendar ed = new GregorianCalendar( sd.get(Calendar.YEAR),
sd.get(Calendar.MONTH),
last );
System.out.println( sd.getTime() + " " + ed.getTime() );
sd.add( Calendar.MONTH, 1 );
last = sd.getActualMaximum(Calendar.DAY_OF_MONTH);
ed = new GregorianCalendar( sd.get(Calendar.YEAR),
sd.get(Calendar.MONTH),
last );
System.out.println( sd.getTime() + " " + ed.getTime() );
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.