This question already has answers here:
How can I calculate a time difference in Java?
(19 answers)
Closed 9 years ago.
I have two hh:mm strings, and I want to make comparisons between them.
I mean, I would want to add or subtract them, make operations. I have a string with the current time and another string that says, for example, "15:00". I want to know how many minutes there are between both strings, result that I can take by doing a subtraction.
Is that possible?
You can parse it by using SimpleDateFormat, then use the getTime() method from Date class to obtain the difference in milliseconds.
DateFormat f = new SimpleDateFormat("hh:mm");
Date d1 = f.parse(s1);
Date d2 = f.parse(s2);
long difference = d1.getTime() - d2.getTime(); // milliseconds
You could use joda datetime for this:
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
DateTime first = formatter.parseDateTime("15:00");
DateTime second = formatter.parseDateTime("15:49");
Interval interval = new Interval(first, second);
System.err.println(interval.toDuration().getStandardMinutes());
}
Have a look here
Using Duration also gives you some other neat methods like getStandardSeconds() which would give you 2940 for this case.
This will get you started.. Do the following for the two strings & then do the necessary comparisions/add/subtract
String time1 = "15:00";
String time2 = "16:00";
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date date1 = sdf.parse(time1);
Date date2 = sdf.parse(time2);
long milliSecondsDiff = date1.getTime() - date2.getTime(); //in milliseconds
int seconds = milliSecondsDiff/1000; //seconds
int minutes = seconds/60; //minutes
Related
This question already has answers here:
Convert linux timestamp to android date
(4 answers)
Closed 5 years ago.
I am new to Android Studio and have ran into a problem - I am trying to carry out a calculation whereby I need the current date and time in an integer format. I also need the current date and time to then display in a TextBox.
I have declared the date as an integer as follows:
public static int date1 = (int) (new Date().getTime()/1000);
datedisplay = (TextView) findViewById(R.id.date);
Then I have tried to get the current date and time displayed in a textbox, but it isn't displaying. I was just wondering would anyone know why?
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
System.out.println(new Date(new Date(date1).getTime()));
datedisplay.setText(dateFormat.format(date1));
Thank you in advance
Use it in any datatype you want either String or Integer.
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
datedisplay.setText(timeStamp);
new Date().getTime() ; return long value if you diving it by 1000
to convert long to int
better if you use long:
long date1 = new Date().getTime() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));
You can also use Calendar class:
Calendar myCalendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm",Locale.getDefault());
String dateString = sdf.format(myCalendar.getTime());
then
datedisplay.setText(dateString);
If you really want to use a int to store your date representation, just use the number of day since the epoch instead of the number of seconds
new Date().getTime()
/1000 //second
/60 //minute
/60 //hour
/24; //day
This will give you a value that will fit in a int for quite some time.
But of course you won't be able to get back the exact precision, if you want the Time part of the Date, you won't be able to. This only allows you to get the Date like yyyy-MM-dd
private static final long EPOCH_DAY = 1000L * 60 * 60 * 24;
public static void main(String[] args){
int i = (int) (new Date().getTime()/EPOCH_DAY);
System.out.println(new Date(i * EPOCH_DAY));
}
Fri Nov 03 01:00:00 CET 2017
(the hours is because of my local being in GMT+1)
This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 5 years ago.
I want to convert unix timestamp to only the current day, like the current day of the month of current day of the year, is it possible to do only using math, like *, /, or something?
The short solution is something like
long epoch = 1501350790; // current unix time
int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(epoch * 1000L)));
it is possible to get this result by calculation (* and /) but there is no easy way. you can use the implementation of java.util.GregorianCalendar as reference
You can use SimpleDateFormat to format your date:
long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
You can also convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
After doing it, you can get what you want:
Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);
You can calculate the date from a unix timestamp with java.util.Date
You need to multiply the timestamp with 1000, because java expects milliseconds. You can use the cal.get(Calendar.DAY_OF_MONTH) function to print the day.
import java.sql.Timestamp;
import java.util.Calendar;
public class MyFirstJavaProgram {
public static void main(String []args) {
long unixTimeStamp= System.currentTimeMillis() / 1000L;
java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
Calendar cal = Calendar.getInstance();
// It's a good point better use cal because date-functions are deprecated
cal.setTime(time);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
}
Any further questions please leave a comment.
This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 6 years ago.
I just needed a sample code block or suggestion to convert the following date string to utc time and find difference with current time in java?
date string "2016-03-21T15:58:36-04:00"
Thanks in advance
You need to format the date string in following way:
String string = "2016-03-21T15:58:36-04:00";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
Date date = format.parse(string);
Then you just need to use Date APIs to find the time difference.
public static long getMillisFrom(String inStrDate) {
DateFormat ISO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
Date inDate = ISO_DATE_FORMAT.parse(inStrDate);
Date curDate = new Date();
long diffMillis = curDate().getTime() - inDate.getTime();
return diffMillis
}
This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 9 years ago.
I need to convert a String which is a epoch (Unix time) format to a Date class an after a String formatted (dd/MM/yyyy).
Thank you for your help !
Unix time is the number of seconds since 1 January 1970, so this should work
Date date = new Date(unixTime * 1000);
String str = new SimpleDateFormat("dd/MM/yyyy").format(date);
BTW SimpleDateFormat accepts millis as argument too, so it is possible to get the same result as
String str = new SimpleDateFormat("dd/MM/yyyy").format(unixTime * 1000);
Date date = new Date(time);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
How can I convert the difference of the current time a given time to create a string with the time format: HH:mm ? ex. 18:36
I did the following but, it is not 24Hour format, it will add AM/PM to the end, and it is 3 hours off.
java.util.Date today = new java.util.Date();
java.sql.Timestamp ts1 = new java.sql.Timestamp(today.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
java.util.Date parsedDate = dateFormat.parse(time);
java.sql.Timestamp ts2 = new java.sql.Timestamp(parsedDate.getTime());
long nowTime = ts1.getTime();
long givenTime = ts2.getTime();
long timeDiff = givenTime - nowTime;
//convert to string
java.util.Date d = new java.util.Date(timeDiff);
result = DateFormat.getTimeInstance(DateFormat.SHORT).format(d);
//Outputs: 6:56 PM for example
Once easy thing you can do is call getTime() for both dates and then subtract them like so:
long timeDiff = today.getTime() - ts1.getTime()
That should give you the difference in miliseconds between the two times. After that you know that one second is 1k miliseconds, 1min i 60s, 1h is 60 minutes and so on.
Take a look at Commons Lang DurationFormatUtils.
Or Joda-Time's PeriodFormatter.