I want to compare two date objects like this:
String format = "MM/dd/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
fakeDate = sdf.parse("15/07/2013 11:00 AM");
fakeDate2 = sdf.parse("15/07/2013 12:00 AM");
int diff = date2.getHours() - date1.getHours();
but then I see getHours is deprecated.
So i have used:
Calendar calendar1 = Calendar.getInstance();
calendar.setTime(new Date("15/7/2013 11:00AM"));
Calendar calendar2 = Calendar.getInstance();
calendar.setTime(new Date("11/7/2013 12:00AM"));
calendar1.get(Calendar.HOUR_OF_DAY) - calendar2.get(Calendar.HOUR_OF_DAY)
but then I see the diff is zero. I guess i change the same calendar instance all the time and compare it to itself. no?
how would you write this?
new Date("15/7/2013 11:00AM")
is not the correct way to construct a Date object. It's deprecated also. Use proper SimpleDateFormat as you are doing well in your first example.
The format MM/dd/yyyy hh:mm a is not correct as per the input date string.
It should be like this.
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date fakeDate = sdf.parse("15/07/2013 11:00 AM");
Date fakeDate2 = sdf.parse("15/07/2013 12:00 AM");
Calendar cal = Calendar.getInstance();
cal.setTime(fakeDate); //set time to first date
int hours1 = cal.get(Calendar.HOUR); // get the hours
cal.setTime(fakeDate2); // set time to second date
int hours2 = cal.get(Calendar.HOUR); // get the hours
System.out.println(hours1 - hours2); // 11 hours
You seemed really confused though it is depreciated this code shall give you a difference of 11 hours which makes sense
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Date fakeDate = dateFormat.parse("15/07/2013 11:00 AM");
Date fakeDate2 = dateFormat.parse("15/07/2013 12:00 AM");
System.out.println(fakeDate.getHours()-fakeDate2.getHours());
Or if you are so interested to use Calendar do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(fakeDate);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(fakeDate2);
System.out.println(calendar.get(Calendar.HOUR_OF_DAY) -
calendar2.get(Calendar.HOUR_OF_DAY));
You will get the same 11 hours difference or simply do it this way
long millisForNewDate = toDate.getTime();
long millisForOldDate = fromDate.getTime();
long difference = millisForNewDate - millisForOldDate;
int hoursDifferenceBetweenDates = (int)(difference/(1000*60*60));
Related
I am given an input date string for ex:2015-06-02 12:60:30 and the output should be 2015-06-02 00:00:00 i.e how to set the HH:mm:ss to zero in the given format yyyy-MM-dd HH:mm:ss ?
use yyyy-MM-dd 00:00:00 format instead of yyyy-MM-dd HH:mm:ss
it will change the hours, minutes and seconds to zero instead of actual values
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String dateValue = dateFormat.format(new Date());
System.out.println(dateValue);
You can try to use this:
calendar.set(Calendar.HOUR_OF_DAY, 0);
Something like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
System.out.println(sdf.format(c.getTime()));
c.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(c.getTime()));
Simply provide a format for the portion of the "date" you want to keep, for example...
String text = "2015-06-02 12:60:30";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(text);
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(out.format(date));
Outputs...
2015-06-02 00:00:00
This is a little trick, which is actually described in the JavaDocs
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
Emphasis added by me
try this
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
String strDate = sm.format(myDate);
If you don't require validation of the input format, you could use a regular expression:
input.replaceAll("\d\d:\d\d:\d\d", "00:00:00")
However, note that this conversion is not necessarily one which yields a valid time: midnight might not be valid, depending upon the date you are converting and its time zone, so this might not yield a valid time. (The start of daylight savings time in Asia/Gaza is the oft-cited example).
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2015);
cal.set(Calendar.MONTH,6);
cal.set(Calendar.HOUR_OF_DAY,2);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date d = cal.getTime();
And to format it you can use:
SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted = sdFormat.format(cal.getTime());
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 have a unix timestamp. I wanted to convert into hours,min and seconds.I wanted to acheive it in java.I tried this .But I am not sure how do i have to concatenate it to hours+min+sec
int day = (int)TimeUnit.SECONDS.toDays(timeStamp);
long hours = TimeUnit.SECONDS.toHours(timeStamp) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(timeStamp) - (TimeUnit.SECONDS.toHours(timeStamp)* 60);
long second = TimeUnit.SECONDS.toSeconds(timeStamp) - (TimeUnit.SECONDS.toMinutes(timeStamp) *60);
thanks,
Ramya.
You can use the Calendar class for this. You can format the time using SimpleDateFormat
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
Date date = new Date ();
date.setTime((long)unix_time*1000);
SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a",Locale.ENGLISH);
System.out.println(df.format(date));
I want to increment the date by one. I have the below code while running the code I am getting unparseable date finally I want the date as string in the format of MM-DD-YYYY.
But same program is working with the YYYY-MM-DD format but i want mydate in this format(MM-DD-YYYY)
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);
Can anyone please help me?
The code should be working fine as long as dt and days are correct. This gave me 12-18-2014:
String dt = "12-17-2014"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
You have to use two different DateFormats:
one for parsing the string and one for formatting.
String dt = schReq.getStartDate(); // Start date
SimpleDateFormat sdf_parser = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf_parser.parse(dt));
c.add(Calendar.DATE, days); // number of days to add
dt = sdf.format(c.getTime());
schReq.setStartDate(dt);
I need to get the month and day of today's date and offset dates. This is how I do it:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_WEEK, 0);
Date today = calendar.getTime();
System.out.println(today);
Output:
Wed Aug 27 15:07:35 CEST 2014
Two things, I need the month and the day to be numeric, like 8/27. I understand how to do that with today's date like so:
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
String a = String.valueOf(day);
String b = String.valueOf(month);
System.out.println(b +"/" + a);
My issue is that I might need to add an offset to that date, if I want tomorrows date for example. Is there a way to do that because converting Wed Aug 27.... to 8/27 would just be a pain. Thanks
Use simple date format:
Something like:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_WEEK, 1);
Date today = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(today));
DateFormat formatter = new SimpleDateFormat("MM/dd");
Calendar cal = Calendar.getInstance();
String calAsString = formatter.format(cal.getTime());
System.out.println(calAsString);
// Now for tomorrow's date:
int offset = 1;
cal.add(Calendar.DATE, offset);
calAsString = formatter.format(cal.getTime());
System.out.println(calAsString);
Use the Calendar to add a value to the day:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH,1)