How to get readable time from currentTimeMillis() [duplicate] - java

This question already has answers here:
How to transform currentTimeMillis to a readable date format? [duplicate]
(2 answers)
Closed 9 years ago.
So below there's a simple way to get a readout from current time millis, but how do I get from my millisecond value to a readable time? Would I be just a stack of modulus that are dividing incrementally by 60? (exception being 100 milliseconds to a second)
Would I be right in thinking/doing that?
Thanks in advance for any help you can give
public class DisplayTime {
public static void main(String[] args) {
System.out.print("Current time in milliseconds = ");
System.out.println(System.currentTimeMillis());
}
}

You may try like this:-
long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

Use that value with a Calendar object
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
String date = c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH);
String time = c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
System.out.println(date + " " + time);
Output:
2013-8-21 16:27:31
Note: c.getInstance() already holds the current datetime, so the second line is redundant. I added it to show how to set the time in millis to the Calendar object

System.out.println(new java.util.Date());
is the same as
System.out.println(new java.util.Date(System.currentTimeMillis()));
bothe represent the current time in a readable format

Related

Finding difference between dates in java [duplicate]

This question already has answers here:
Calculating difference in dates in Java
(7 answers)
Closed 6 years ago.
I am new to java. I am having slight confusion regarding date arithmetic in java. I have following scenario, where I want to find differences between two dates :-
java.util.Date objDt1 = getDate1FromSrc1(); // I am obtaining it from src1
java.util.Date objDt2 = getDate2FromOtherSrc(); // I am getting dt2 by other way.
Now, I want to find difference between two dates and the output must be other date object.
So, I have written the following code :-
Calendar objCal1 = Calendar.getInstance();
Calendar objCal2 = Calendar.getInstance();
objCal1.setTime(objDt1);
objCal2.setTime(objDt2);
objCal1.add(Calendar.DAY_OF_MONTH, -objCal2.get(Calendar.DAY_OF_MONTH));
objCal1.add(Calendar.MONTH, -objCal2.get(Calendar.MONTH));
objCal1.add(Calendar.YEAR, -objCal2.get(Calendar.YEAR));
objCal1.add(Calendar.HOUR_OF_DAY, -objCal2.get(Calendar.HOUR_OF_DAY));
objCal1.add(Calendar.MINUTE, -objCal2.get(Calendar.MINUTE));
objCal1.add(Calendar.SECOND, -objCal2.get(Calendar.SECOND));
java.util.Date objDiff = objCal1.getTime();
But, I am getting some wierd results. Eg. If objDt1 is "02/22/2016 09:00:00" and objDt2 is "02/22/2016 11:00:00", then I am expecting objDiff to be "02:00:00" as output, which I am not getting.
Can you suggest me what's wrong I am doing here and what's the right way to approach this problem ?
Thanks in advance.
In order to find the difference between two dates you can simply convert it to long as follows:
java.util.Date objDt1 = getDate1FromSrc1();
java.util.Date objDt2 = getDate2FromOtherSrc();
long date1 = objDt1.getTime();
long date2 = objDt2.getTime();
System.out.println("Difference (In Seconds): " + (date2 - date1)/1000);
If you want this difference to be in HH:mm:ss format then you can do something like this:
public static void main (String[] args) throws Exception
{
SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
java.util.Date objDt1 = getDate1FromSrc1();
java.util.Date objDt2 = getDate2FromOtherSrc();
long date1 = objDt1.getTime();
long date2 = objDt2.getTime();
System.out.println("Difference: " + sf.format(new Date((date2 - date1)/1000)));
}

Convert Date.toString() back to Date in Java [duplicate]

This question already has answers here:
How to add 10 minutes to my (String) time?
(8 answers)
How can I read and parse a date and time in Android?
(2 answers)
Closed 7 years ago.
I am calling an API and as per the guidelines calling it every time is inefficient as the data does not change that regularly. They recommend calling it once and then not polling until 10 minutes has passed.
I am calling this from an Android app and so I want to store the current date plus 10 minutes. I do this like so:
Date forecastRefreshDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(forecastRefreshDate);
cal.add(Calendar.MINUTE, 10);
editor.putString("ForecastRefreshDate", forecastRefreshDate.toString());
editor.apply();
So now when this code is run again it needs to check if the current time (new Date()) is > the value saved in the cache/app file.
How do I create a Date variable equal to the value stored in the cache as a String?
Convert date to epoch time, which is a number of milliseconds stored as a long. Store long as string and parse back into long when needed.
long epoch = date.getTime(); //where date is your Date
String yourString = Long.toString(epoch); //to string for storage
long time = Long.valueOf(yourString).longValue(); ; //back to epoch
Date originaldate = new Date(Long.parseLong(time)); //back to date
When dealing with time, which is needed only internally to measure time periods,
It is much better to store timestamps as long value (millis sicne 1.1.1970 UTC).
Use long timestamp = System.currentTimeMillis()
If a String storage is neccesary simply convert the Long to a String.
String timeStampStr = String.parseLong(timeStamp);
Do not use Date.toString for other things than for logging or debugging.
The toString() representation may be different in other countries.
If a human readable timestamp string is needed you have to specify a Specific DateFormat, see also DateFormatter.
Parsing a long it the most efficent way, however there may be cases that you have already formatted a date to some other format and want to parse that. Then you should use this
private static final String format = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
private Calendar dateTime = Calendar.getInstance();
public void setDateTime(String dateTimeString) {
try {
dateTime.setTime(formatter.parse(dateTimeString));
} catch (ParseException e) {
// Dummy handled exception
dateTime.setTimeInMillis(0);
}
}
Parse a long containing milliseconds since epoch
Date date = new Date(Long.parseLong(timeInMillisecondsString));
Since you're using a plain toString() it should be coverable using a SimpleDateFormat.
Try this:
DateFormat dateFormat = new SimpleDateFormat();
Date myDate = dateFormat.parse(myDateString);

how do i get the difference between two dates in days in java [duplicate]

This question already has answers here:
Difference in days between two dates in Java?
(19 answers)
Closed 8 years ago.
i am trying to get the difference between two dates. one of the dates was parsed from a string(dateEmployd) and the other date is the current date (currentDate). This is what i did to get the dates...
public static Date getActiveService(String DtEmplydString){
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");//formater for parsed String date
Date dateEmployd, currentDate,periodDifference = null;
try{
dateEmployd = ft.parse(DtEmplydString);
currentDate = new Date();
}catch(ParseException e){
JOptionPane.showMessageDialog(null, e);
}
return periodDifference;
}
Now, i am meant to return periodDifference but i dont know how i would find the difference betweent the two dates (dateEmployd and currentDate) and display it in years or days or a combination of both.
please guys much help is needed. thanks in advance...
Take a look at the jodatime library. They have functions like
DateTime dateEmployd = DateTimeFormat.forPattern("yyyy-MM-dd").parse(DtEmplydString);
Years.yearsBetween(dateEmployd, DateTime.now())
The same for Days.daysbetween, Seconds, Hours etc.
long diff = date2.getTime() - date1.getTime();
You could try out the Java.Calendar for date functions because Date is deprecated .
Here is an example with Cdate comparators
Calendar start = Calendar.getInstance();
start.setTime(from ( your initial Date object here ) );
Calendar end = Calendar.getInstance();
end.setTime(new Date());
int actualDays = start.compareTo(end);

How to get time on Android phone programmatically? [duplicate]

This question already has answers here:
How to get current time and date in Android
(42 answers)
Closed 8 years ago.
I am using this Java method here to get the current time:
final Date d = new Date();
d.getTime();
1390283202624
What I am getting a numeric figure of datatype long. What I need is the exact time in the format hh:mm:ss. And in the end I also have to perform arithmetic on the figure obtained.
Any clue? Also is this a reliable way of obtaining time on Android phone because I am getting a constant value here?
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
String formattedDate = sdf.format(d);
System.out.println(formattedDate);
Calendar instance = Calendar.getInstance();
int hour = instance.get(Calendar.HOUR);
int minute = instance.get(Calendar.MINUTE);
int second = instance.get(Calendar.SECOND);
use:
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
String time=sdf.format(new Date());
Use Calendar class.
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
See this question. Calendar class contain all desired information.

How to add 10 minutes to my (String) time?

I have this time:
String myTime = "14:10";
Now I want to add 10 minutes to this time, so that it would be 14:20
How can I achieve this?
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
I would use Joda Time, parse the time as a LocalTime, and then use
time = time.plusMinutes(10);
Short but complete program to demonstrate this:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time = formatter.parseLocalTime("14:10");
time = time.plusMinutes(10);
System.out.println(formatter.print(time));
}
}
Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.
Use Calendar.add(int field,int amount) method.
Java 7 Time API
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
LocalTime lt = LocalTime.parse("14:10");
System.out.println(df.format(lt.plusMinutes(10)));
You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
You have a plenty of easy approaches within above answers.
This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

Categories

Resources