I'm designing a program where in my recylerview i wanted to display a list of items whose date is 4 days less or more than current date.
This will work for month:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
This will work for -4 day:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
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 want to convert the calendar object between two time zones in java.I shall the pass the first calendar object and want the output to be the modified calendar object with the different timezone.
Can someone provide me a way on how to do it ?
This is what i have done ...
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
GregorianCalendar pst = new GregorianCalendar();
GregorianCalendar est = new GregorianCalendar();
pst.setTime(maintWindow);
int year = pst.get(Calendar.YEAR);
int month = pst.get(Calendar.MONTH);
int day = pst.get(Calendar.DAY_OF_MONTH);
format.setTimeZone(timeZone);
pst.set(year, month, day, hour, min);
Date date = pst.getTime();
logger.info(date);
logger.info(format.format(date));
logger.info(pst.getTime());
est.setTimeInMillis(date.getTime());
logger.info(est.getTime());
You can use Calendar.setTimeZone.
For example if you have a Calendar reference cal initialized with any time zone, a call to the method like this
cal.setTimeZone(TimeZone.getTimeZone("GMT"))
modifies the time zone of cal to GMT.
I have some date and I want to get last x day before this date so this is my code:
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, -x);
date = new Date(today.getTimeInMillis()))
this code works only if some day is actual day. How I can change it. Is there some method to get calendar from date ?
Use the setTime method to set the date of your calendar :
Calendar aDay = Calendar.getInstance();
aDay.setTime(aDate);
I want a javascript or java program should always give date 1st of current month.
Is there any tech?
You can use Calendar for Java
Date date = new Date(System.currentTimeMillis());
cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
Now you do what every you want to do with this Calendar object like to get the Day of the Week (Sat, Sun, .... )
int weekday = cal.get(Calendar.DAY_OF_WEEK);
And for JavaScript you can use:
var theFirst = new Date();
theFirst.setDate(1);
setDate sets the day of the month for the Date object (from 1 to 31). Then you can do whatever you want with theFirst, like get the day of the week.
Calendar ans = Calendar.getInstance();
ans.set(ans.get(Calendar.YEAR),
ans.get(Calendar.MONTH),
1,
0,
0,
0
);
System.out.println(ans.getTime());