How to get selected month last date last timestamp in java? - java

From the below java code I'm getting a month First & last dateTimestamp, but here i need last dateTimestamp as - "Mon Aug 31 23:59:59 IST 2015" instead of - "Mon Aug 31 00:00:00 IST 2015"?
Calendar cal = Calendar.getInstance();
int year = 2015;
int month = 07;
cal.set(cal.DATE,1);
cal.set(cal.YEAR,year);
cal.set(cal.MONTH, month);
String firstDate = (cal.getActualMinimum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("firstDate-->"+"\t"+firstDate);
String lastDate = (cal.getActualMaximum(cal.DATE) + "/" + (month+1) + "/" +year);
System.out.println("lastDate-->"+"\t"+lastDate);
DateFormat firstFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = firstFormat.parse(firstDate);
System.out.println("BeginDate Timestamp"+ "\t" + beginDate);
DateFormat secoundFormat = new SimpleDateFormat("dd/MM/yyyy");
Date endDate = secoundFormat.parse(lastDate);
System.out.println("endDate Timestamp"+ "\t" + endDate);
Output:->
firstDate--> 1/8/2015
lastDate--> 31/8/2015
BeginDate Timestamp Sat Aug 01 00:00:00 IST 2015
endDate Timestamp Mon Aug 31 00:00:00 IST 2015
Please help me if we have any solution.

If I understand your question, it looks as if you want to pass a year and month into a method, and get back the last day of the passed month.
I would suggest consider (in this order):
which jdk you use
configuration of calendar
configuration of timezone (maybe)
using jodatime
As of 1.8 many JodaTime-like features have been added to the jdk- e.g. see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html (If you arent using 1.8 you can use the joda lib, assuming your organization allows it)
Calendar.getInstance() gives a default TimeZone and a default Locale, which means the definitions of the running JVM. You may or may not need to consider this and implement more than just getInstance(). See API javadoc.
Assuming a Gregeorian Calendar (hey, you could be Bahaian and have 19 months in the year ...) , here is one partial implementation using JDK 1.7, JodaTime jar 2.2, validation-1.0.0.GA jar:
#Test
public void testDate() {
final String dateStringOfFirstDay = "1.7.2015";
final Date lastDayOfMonth = getLastDayOfMonth(dateStringOfFirstDay);
Assert.assertNotNull(lastDayOfMonth);
//more assertions ...
}
private Date getLastDayOfMonth(#NotNull String dateStringOfFirstDay) {
//further validation here necessary according to required date format
DateTime dt = DateTime.parse(dateStringOfFirstDay);
return dt.dayOfMonth().withMaximumValue().toDate();
}
The defintion of DateFormat/DateTimeFormat and further result assertions is left up to you.
Best of luck!

Guys I got a solution for my question!!!
I think it will help u too...
Calendar calendar = Calendar.getInstance();
int year=2015;
int month=7;
int date=31;
int hourOfDay=23;
int minute=59;
int second=59;
int milliSecond=999;
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.set(calendar.MILLISECOND, milliSecond);
System.out.println("Time from Calendar: "+calendar.getTime());
long timeInMilliSeconds=calendar.getTimeInMillis();
System.out.println("timeInMilliSeconds from calendar: "+timeInMilliSeconds);
Timestamp timestamp=new Timestamp(timeInMilliSeconds);
System.out.println(timestamp);
The above program gives the last date last timestamp in a selected month.
getTimeInMillis() takes the time from Jan 01, 1970 to current time in Milliseconds.
Using those milliseconds i'm getting the Timestamp.
Thank you for your help guys!!!
OutPut:->
Time from Calendar: Mon Aug 31 23:59:59 IST 2015
timeInMilliSeconds from calendar: 1441045799999
2015-08-31 23:59:59.999

Related

How to calculate next week?

I want to precisely calculate the time one week from a given date, but the output I get back is one hour early.
code:
long DURATION = 7 * 24 * 60 * 60 * 1000;
System.out.println(" now: " + new Date(System.currentTimeMillis()));
System.out.println("next week: " + new Date(System.currentTimeMillis() + DURATION));
output:
now: Wed Sep 16 09:52:36 IRDT 2015
next week: Wed Sep 23 08:52:36 IRST 2015
How can I calculate this correctly?
Never, ever rely on millisecond arithmetic, there are too many rules and gotchas to make it of any worth (even over a small span of time), instead use a dedicated library, like Java 8's Time API, JodaTime or even Calendar
Java 8
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);
System.out.println(now);
System.out.println(then);
Which outputs
2015-09-16T15:34:14.771
2015-09-23T15:34:14.771
JodaTime
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.plusDays(7);
System.out.println(now);
System.out.println(then);
Which outputs
2015-09-16T15:35:19.954
2015-09-23T15:35:19.954
Calendar
When you can't use Java 8 or JodaTime
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DATE, 7);
Date then = cal.getTime();
System.out.println(now);
System.out.println(then);
Which outputs
Wed Sep 16 15:36:39 EST 2015
Wed Sep 23 15:36:39 EST 2015
nb: The "problem" you seem to be having, isn't a problem at all, but simply the fact that over the period, your time zone seems to have entered/exited day light savings, so Date is displaying the time, with it's correct offset
Try this
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(cal.getTime());
The difference is because of the different timezone. IRDT is +0430 and IRST is +0330
To overcome this issue you can use the JodaTime.
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextweek = now.plusDays(7);
System.out.println(now);
System.out.println(nextweek);
As other said. It would be better to use Calendar or JodaTime library. But the question is why you were not getting the desired result. It was because currentTimeMillis() calculates time between "computer time" and coordinated universal time (UTC). Now consider following case.
long DURATION = 7 * 24 * 60 * 60 * 1000;
Date now = new Date();
Date nextWeek = new Date(now.getTime() + DURATION);
System.out.println(" now: " + now);
System.out.println("next week: " + nextWeek);
here Date.getTime() calculate time from 00:00:00 GMT every time and then when converted to string will give time for your local time zone.
Edit :
I was wrong. The reason is as simon said.
The actual "why" is that IRDT (Iran Daylight Time) ends on September
22nd. That's why the first date (September 16th) in the OP's post is
displayed as IRDT and the second date (September 23rd) is displayed as
IRST. Because IRST (Iran Standard Time) is one hour earlier than IRDT
the time displayed is 08:52:36 instead of 09:52:36.

how can i get current system date in Android?

I am getting date in 28/12/2013 format, but I need current date in a String format,
like
Thursday, August 21
so that I can set over TextView,
Explain a bit, if you think something is necessary, I am new to Android Development.
You can always refer to the documentation.
http://developer.android.com/reference/java/util/Date.html
In the documentation you will find this:
Calendar.get(Calendar.MONTH)
public int getMonth () #old do not use
Returns the gregorian calendar month for this Date object.
Calendar.get(Calendar.YEAR
public int getYear () #old do not use
Returns the gregorian calendar year since 1900 for this Date object.
Calendar.get(Calendar.DAY_OF_WEEK)
public int getDay () #old do not use
Returns the gregorian calendar day of the week for this Date object.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMM dd");
String formatedDate = sdf.format(your_date);
At the moment I haven't programmed any android app, I'll do that in the future. But I have found that here. It may soulve your problem hopefully.
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateInstance(),
DateFormat.getDateTimeInstance(),
DateFormat.getTimeInstance(),
};
for (DateFormat df : formats) {
System.out.println(df.format(new Date(0)));
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(new Date(0)));
}
Produces this output when run on an en_US device in the America/Los_Angeles time zone:
Dec 31, 1969
Jan 1, 1970
Dec 31, 1969 4:00:00 PM
Jan 1, 1970 12:00:00 AM
4:00:00 PM
12:00:00 AM

Get correct long value from parsed Date (Timezone issue)

I'm trying to parse a date from a String and get the long value. The long value will be later sent to an SQL query.
here's my code:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date day = new Date();
try {
day = sdf.parse(dayDate);
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
which gives the following output:
day : Thu Feb 28 00:00:00 EET 2013 long : 1362002400000
which is correct but not what I want since the long value results in Wed, 27 Feb 2013 22:00:00 GMT (http://www.epochconverter.com/) (I'm in a GMT+2 timezone). And i need to send to correct long value to sql.
Is there anyway to work around this without using external libraries?
SimpleDateFormat is locale-aware, meaning the date it parses is in your timezone. Midnight 28 Feb in GMT+2 is actually 10pm 27 Feb in GMT, the long value 1362002400000. I would add this to get the parsing right (would't bother using Calendar):
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
Again, when you print this date it uses SimpleDateFormat and that's why you can see EET in the output.
Passing this to database is a different story though once you get this right.
Use DateFormat.setCalendar(Calendar cal) to set a Calendar with GMT as its timezone, or use DateFormat.setTimeZone(TimeZone zone) with the GMT TimeZone. That will ensure that the resulting Date will be 00:00:00 in GMT instead of in EET.
If you add a timezone specifier to your string you can force java to use GMT for the conversion:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy z"); // z is a timezone specifier
Date day = new Date();
try {
day = sdf.parse(dayDate + " GMT"); // Use GMT timezone.
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
You are converting between text and internal (Date) representations of dates and times without explicitly stating the time-zone. That never goes well.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date = calendar.getTime();
Use your timezone String:
TimeZones

Date/time conversion/arithmetic

I've below code in Java 1.7:
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("07/28/12 01:00 AM, PST");
The above date time (07/28/12 01:00 AM, PST) is in the properties file which is configurable. If this date time is already passed, then I need to get the current date, set the time part from above string which is 01:00 AM PST in the current date & if this time is also already passed, then get the next day & set the time part from above string in it. The final object should be Date since I need to use it in Timer object.
How can I do this efficiently? Should I convert from date to Calendar or vice-versa? Can any one provide snippet?
You should look into the Calendar class. You can use constructs like:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DAY_OF_YEAR, 1);
It also has methods for checking if your startDate is before() or after() a new date (use the current time).
While writing of the built-in Java date/time structure, i would be remiss if i didnt plug Joda Time, considered by many to be superior to the native Java implementation.
EDIT:
It would be more efficient to show an example of the Date.compareTo() process, as the Calendar.before() and Calendar.after() require comparisons against other Calendar objects, which can be expensive to create.
take a look at the following:
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("07/28/12 01:00 AM, PST");
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
Date now = new Date();
if (startDate.compareTo(now)< 0) {
System.out.println("start date: " + startDate + " is before " + now);
Calendar nowCal = Calendar.getInstance();
nowCal.add(Calendar.DAY_OF_YEAR,1);
cal.set(Calendar.DAY_OF_YEAR, nowCal.get(Calendar.DAY_OF_YEAR));
} else if (startDate.compareTo(now) == 0) {
System.out.println("startDate: " +startDate + " is equal to " + now);
} else {
System.out.println("startDate: " + cal + " is after " + now);
}
System.out.println(cal.getTime());
I think this should work...your algorthim has my head spinning a little and I'm in a different time zone, so you original string didn't work :P
try {
DateFormat df = DateFormat.getInstance();
Date startDate = df.parse("28/07/2012 01:00 AM");
System.out.println("StartDate = " + startDate);
Date callDate = startDate;
Calendar today = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime(startDate);
System.out.println("Today = " + today.getTime());
// If this date time is already passed
// Tue Jul 31 12:18:09 EST 2012 is after Sat Jul 28 01:00:00 EST 2012
if (today.after(start)) {
//then I need to get the current date, set the time part from above string in the current date
Calendar timeMatch = Calendar.getInstance();
timeMatch.setTime(startDate);
timeMatch.set(Calendar.DATE, today.get(Calendar.DATE));
timeMatch.set(Calendar.MONTH, today.get(Calendar.MONTH));
timeMatch.set(Calendar.YEAR, today.get(Calendar.YEAR));
//& if this time is also already passed, then get the next day & set the time part from above string in it
if (timeMatch.after(today)) {
timeMatch.add(Calendar.DATE, 1);
}
callDate = timeMatch.getTime();
}
System.out.println("CallDate = " + callDate);
} catch (ParseException exp) {
exp.printStackTrace();
}
This produces the following output
StartDate = Sat Jul 28 01:00:00 EST 2012
Today = Tue Jul 31 12:18:09 EST 2012
CallDate = Tue Jul 31 01:00:00 EST 2012

Java : Get any day in a week from Calendar

Using Calendar I can get the week, year and all details for the current day. How can I navigate to a particualr day in that week?
Say, calendar.get(Calendar.DAY_OF_WEEK); returns 3, which means a Tuesday. Now, I want to go to say Friday for that week or any other day in that week. How can I do that?
Thanks for your replies. I think I need to make the scenario more clear.
Basically, I am trying to disable email alerts in my system during specified period.
I get values like:
disableStart = "FRIDAY-19:00"
disableEnd = "SUNDAY-19:00"
Now, i need to verify if email should be sent at a particular time.
e.g. if today = Thursday any time, send email
but, if today = Saturday any time can't send as per values above.
If I understand correctly you can use the Calendar.set(Field, value) method.
SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(f.format(c.getTime()));
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(f.format(c.getTime()));
Produces the output
6
08-10-2010
3
05-10-2010
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
System.out.println("Today: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("MONDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println("TUESDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
System.out.println("WEDNESDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
System.out.println("THURSDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("FRIDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("SATURDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("SUNDAY: " + c.getTime());
Gives:
Today: Fri Oct 08 15:45:14 CEST 2010
MONDAY: Mon Oct 04 15:45:14 CEST 2010
TUESDAY: Tue Oct 05 15:45:14 CEST 2010
WEDNESDAY: Wed Oct 06 15:45:14 CEST 2010
THURSDAY: Thu Oct 07 15:45:14 CEST 2010
FRIDAY: Fri Oct 08 15:45:14 CEST 2010
SATURDAY: Sat Oct 09 15:45:14 CEST 2010
SUNDAY: Sun Oct 10 15:45:14 CEST 2010
Which seams to mean that, at least on my system, the weeks starts on monday.
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Thanks to Kevin and Maurice for the answers. They really gave me the start point.
I ended with this test code, in case it helps anyone.
private static Date getTimeForAnyDayInWeek(int nDay, int nHour, int nMin)
{
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
Date date = Calendar.getInstance().getTime();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, nDay);
c.set(Calendar.HOUR_OF_DAY, nHour);
c.set(Calendar.MINUTE, nMin);
return c.getTime();
}
public static void main(String[] args)
{
Date start = getTimeForAnyDayInWeek(6, 19, 00);
Date end = getTimeForAnyDayInWeek(8, 19, 00);
Date c = new Date();
if (start.before(c) && c.before(end))
System.out.println("BLOCK");
else
System.out.println("SEND");
}
Thanks,
Anubhav
This is a perfect example of why jodatime is so good, here is my similar code
DateTime dt = new DateTime(); //current datetime, jodatime format
DateTime fridayLastWeek = dt.minusWeeks(1).dayOfWeek().setCopy("Friday");
Date convertedtorubbishdateformat = fridayLastWeek.toDate();
I used to waste so much time witht he standard java date/calendar. Then i got jodatime, you wont regret, it apparently will be used as part of standard java in the future. I didn;t bother downlaoding the jar for for ages, I wish I had done, you won't regret it.

Categories