I have to parse a string to a date, let us say givenDate, to EST timezone.
Also, I have to take the current date, let us say currentDate in EST timezone.
My current timezone is IST (GMT+5:30).
If the currentDate is greater than givenDate then I need to add a day to currentDate.
Here is the solution that I have implemented.
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Calendar givenDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
givenDate .setTime(df.parse("01/08/2016"));
Calendar currentDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
if(currentDate.get(Calendar.YEAR) > givenDate .get(Calendar.YEAR) ||
currentDate.get(Calendar.DAY_OF_YEAR) > givenDate.get(Calendar.DAY_OF_YEAR)){
currentDate.add(Calendar.DATE, 1);
}
System.out.println("Final date : "+df.format(currentDate.getTime()));
Is there any better solution for this?
Also, the following has been tickling my mind.
Consider code snippet
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Calendar givenDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
givenDate .setTime(df.parse("01/07/2016"));
System.out.println(givenDate .get(Calendar.DATE)); //6
System.out.println(givenDate .get(Calendar.DAY_OF_MONTH)); //6
System.out.println(givenDate .get(Calendar.DAY_OF_YEAR)); //6
Why am I getting 6 for DATE, DAY_OF_MONTH, DAY_OF_YEAR? I would expect
they must return 7 as the given date is 7 days from the starting of
the year 2016.
But if I add the following line after first line of above code, above mentioned fields are returning 7. What could be the reason of this?
df.setTimeZone(TimeZone.getTimeZone("EST"));
.
You need to set the timezone into the SimpleDateFormat class, and then you can compare the parsed Date with the current time:
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("EST"));
Date givenDate = df.parse("01/08/2016");
Calendar currentDate = Calendar.getInstance();
if(currentDate.getTime().compareTo(givenDate) > 0) {
currentTime.add(Calendar.DATE, 1);
}
Keep in mind that a Date object represents the current time (number of seconds since epoch) in UTC timezone.
Related
I was trying to add current time into previous date. But it was adding in current date with time not with previous date.
see my bellow code:
Date startUserDate = ;//this is my previous date object;
startUserDate.setTime(new Date().getTime());// here i'm trying to add current time in previous date.
System.out.println("current time with previous Date :"+startUserDate);
In previous date there is no time and i want to add current time in previous date.I can do this, please help me out.
Use calendar object
Get instance of calendar object and set your past time to it
Date startUserDate = ;
Calendar calendar = Calendar.getInstance();
calendar.settime(startUserDate);
Create new calendar instance
Calendar cal = Calendar.getInstance();
cal.settime(new Date());
format the date to get string representation of time of current date
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(cal.getTime());
split that string to get hour minute and second object
String hh = expiry.split(":")[0];
String mm = expiry.split(":")[1];
String ss = expiry.split(":")[2];
add it to the previous calendar object
calendar .add(Calendar.HOUR_OF_DAY, hh);
calendar .add(Calendar.MINUTE, mm);
calendar .add(Calendar.SECOND, ss);
this date will have current time added to your date
Date newDate = calendar.getTime;
Use Calendar:
first set the date/time of the first calendar object to the old date
object use as second Calendar object to set the current time on the
first calendar object then convert it back to date
as follow:
//E.g. for startUserDate
Date startUserDate = new Date(System.currentTimeMillis() - (24L * 60L * 60L * 1000L) - (60L * 60L * 1000L));//minus 1 day and 1 hour
Calendar calDateThen = Calendar.getInstance();
Calendar calTimeNow = Calendar.getInstance();
calDateThen.setTime(startUserDate);
calDateThen.set(Calendar.HOUR_OF_DAY, calTimeNow.get(Calendar.HOUR_OF_DAY));
calDateThen.set(Calendar.MINUTE, calTimeNow.get(Calendar.MINUTE));
calDateThen.set(Calendar.SECOND, calTimeNow.get(Calendar.SECOND));
startUserDate = calDateThen.getTime();
System.out.println(startUserDate);
The second Calendar object calTimeNow can be replaced with Calendar.getInstance() where it is used.
You can do it using DateFormat and String, here's the solution that you need:
Code:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String timeString = df.format(new Date()).substring(10); // 10 is the beginIndex of time here
DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
String startUserDateString = df2.format(startUserDate);
startUserDateString = startUserDateString+" "+timeString;
// you will get this format "MM/dd/yyyy HH:mm:ss"
//then parse the new date here
startUserDate = df.parse(startUserDateString);
Explanation:
Just convert the current date to a string and then extract the time from it using .substring() method, then convert your userDate to a string concatenate the taken time String to it and finally parse this date to get what you need.
Example:
You can see it working in this ideone DEMO.
Which takes 02/20/2002 in input and returns 02/20/2002 04:36:14 as result.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
ZoneId zone = ZoneId.systemDefault();
LocalDate somePreviousDate = LocalDate.of(2018, Month.NOVEMBER, 22);
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = somePreviousDate.atTime(timeOfDayNow);
System.out.println(dateTime);
When I ran the code just now — 16:25 in my time zone — I got this output:
2018-11-22T16:25:53.253892
If you’ve got an old-fashioned Date object, start by converting to a modern Instant and perform further conversion from there:
Date somePreviousDate = new Date(1_555_555_555_555L);
LocalDate date = somePreviousDate.toInstant().atZone(zone).toLocalDate();
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = date.atTime(timeOfDayNow);
2019-04-18T16:25:53.277947
If conversely you need the result as an old-fashioned Date, also convert over Instant:
Instant i = dateTime.atZone(zone).toInstant();
Date oldfasionedDate = Date.from(i);
System.out.println(oldfasionedDate);
Thu Nov 22 16:25:53 CET 2018
Link
Oracle tutorial: Date Time explaining how to use java.time.
The getTime method returns the number of milliseconds since 1970/01/01 so to get the time portion of the date you can either use a Calendar object or simply use modula arithmetic (using the above milliseconds value and the MAX millseconds in a day) to extract the time portion of the Date.
Then when you have the time you need to add it to the second date,
but seriously, use http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
and use things like get (HOUR) and get (MINUTE) etc. which then you can use with set (HOUR, val)
You need to use Calendar class to perform addition to Dateobject. Date's setTime() will set that time in Date object but not add i.e it will overwrite previous date. new Date().getTime() will not return only time portion but time since Epoch. Also, how did you manipulated , startUserDate to not have any time (I mean , was it via Calendar or Formatter) ?
See Answer , Time Portion of Date to calculate only time portion,
long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
Date now = Calendar.getInstance().getTime();
long timePortion = now.getTime() % MILLIS_PER_DAY;
then you can use something like, cal.add(Calendar.MILLISECOND, (int)timePortion); where cal is Calendar object corresponding to your startUserDate in your code.
Calendar calendar = Calendar.getInstance();
calendar.setTime(startUserDate );
//new date for current time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(new Date());
String hhStr = currentdate.split(":")[0];
String mmStr = currentdate.split(":")[1];
String ssStr = currentdate.split(":")[2];
Integer hh = 0;
Integer mm = 0;
Integer ss = 0;
try {
hh = Integer.parseInt(hhStr);
mm = Integer.parseInt(mmStr);
ss = Integer.parseInt(ssStr);
}catch(Exception e) {e.printStackTrace();}
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
startUserDate = calendar.getTime();
I am currently trying to get create a java Date which looks the same no matter what timezone I view it in. My current code is:
Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.JANUARY, 8, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
In my current timeZone this gives me '2015-01-08T00:00:00Z'In another this gives me 2015-01-08T00:00:00-03:00. What I want to know is if there is any way to drop the timezone part so as the time is the same in both time zones.
I would be VERY grateful for any help on this matter. Thank you.
Java SE 8 comes with a new Date & Time API. Have a look at LocalDate and LocalDateTime.
If you are only interested in the format of the time, create a java.text.SimpleDateFormat object to print your time in the format that you want.
http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
If you want the time to be printed with the same numbers no matter the TimeZone,
Use String ids[] = java.util.TimeZone.getAvailableIDs();
to get the TimeZone's IDs and find the ID that you want.
In this example, I created two SimpleDateFormat objects set to two different TimeZones. They both print off the same Calendar object. I have taken off the Z in ft2 to remove the time zone portion. By relying on toString(), I think you would be subject to Locale differences in displaying dates, like US MM/dd/yyyy and UK dd/MM/yyyy.
TimeZone tz = TimeZone.getTimeZone("America/New_York");
TimeZone tz2 = TimeZone.getTimeZone("America/Chicago");
Calendar acal = new GregorianCalendar();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss Z");
ft.setTimeZone(tz);
SimpleDateFormat ft2 = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss");
ft2.setTimeZone(tz2);
String date1 = ft.format(acal.getTime());
System.out.println(date1);
String date2 = ft2.format(acal.getTime());
System.out.println(date2);
Output:
2015-01-08T10:36:39 -0500
2015-01-08T09:36:39
I would like to set the timepart of a calendar. Here is what I'm doing
Calendar calNow = Calendar.getInstance();
Calendar endWait = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date d1 = null;
try {
d1 = sdf.parse("14:45");
}catch(ParseException ex){
logger.error("Error parsing time");
}
endWait.setTime(d1);
Date waitTo = endWait.getTime();
Date now = calNow.getTime();
The "now" variable is correct date and time, however the waitTo was expected to be the date of today and time 14:45, but is tomorrow at 02:45.
For me it is not giving tomorrow, but waitTo = Thu Jan 01 14:45:00 CET 1970.
The reason for this can be found in the javadoc of SimpleDateFormat:
This parsing operation uses the calendar to produce a Date. All of the
calendar's date-time fields are cleared before parsing, and the
calendar's default values of the date-time fields are used for any
missing date-time information. For example, the year value of the
parsed Date is 1970 with GregorianCalendar if no year value is given
from the parsing operation.
Calendar.setTime() will use the date and time information of the passed Date instance.
To only update the hours and minutes of the waitTo you can:
Calendar tmpCal=Calendar.getInstance();
tmpCal.setTime(d1);
endWait.set(Calendar.HOUR_OF_DAY,tmpCal.get(Calendar.HOUR_OF_DAY));
endWait.set(Calendar.MINUTE, tmpCal.get(Calendar.MINUTE));
This way the day, month, year part of the endWait will not be altered.
I have a date say for e.g. current date which is 19/04/2013
And I have number of months given say for e.g. 10
I want to find out the date falling before 10 months from 19/04/2013.
How to achieve it in Java?
For example, if I want to find out date before a week, I can achieve as below:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
But how to find the same for months ?
Well, you could do something similar to your example:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.MONTH, -10);
Date newDate = calendar.getTime();
It'll set newDate to a date 10 months before myDate.
Using jodatime this is so much easier and verbose:
LocalDate date = LocalDate.parse("19/04/2013", DateTimeFormat.forPattern("dd/MM/yyyy"));
LocalDate result = date.minus(Months.TEN);
System.out.println(result.toString("dd/MM/yyyy"));
I need to find wednesday for the two dates given by the user.
example:
Inputs are:
from date:07-Feb-2013
To date:13-feb-2013
The gap between the from date and To date is 7 days always.
Expected Output:12-feb-2013
public String getAutoDayExpiryDateAndToDate(String instrmentId,String deliveryAutoFromDate)
throws SystemException, FunctionalException,ParseException
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(deliveryAutoFromDate));
Date fromDate=calendar.getTime();
SimpleDateFormat sf1 = new SimpleDateFormat("dd-MMM-yyyy");
String formatedDate = sf1.format(fromDate);
calendar.add(Calendar.WEEK_OF_MONTH, 1);
calendar.add(Calendar.DAY_OF_WEEK,-1);
Date time = calendar.getTime();
SimpleDateFormat sf = new SimpleDateFormat("dd-MMM-yyyy");
String formatedDate1 = sf.format(time);
}
after these i need to find Wednesday which is present between formatedDate and formatedDate1 .how can i do it??
Use the Calendar class. Set it to the first date, and then check if the current day of the week is Wednesday by calling calendar.get(Calendar.DAY_OF_WEEK). Perform this check in a loop, adding a day to the current date during each iteration. This will never take more than seven steps, so you don't need to do anything fancier than that.
this should find the first Wednesday after (or equal) the given date
GregorianCalendar c = new GregorianCalendar(2013, 1, 7);
if (c.get(Calendar.DAY_OF_WEEK) <= Calendar.WEDNESDAY) {
c.add(Calendar.DAY_OF_YEAR, Calendar.WEDNESDAY - c.get(Calendar.DAY_OF_WEEK));
} else {
c.add(Calendar.DAY_OF_YEAR, 11 - c.get(Calendar.DAY_OF_WEEK));
}
System.out.println(c.getTime());
prints
Wed Feb 13 00:00:00 EET 2013
you can test it to see if it gives you what you want