This question already has answers here:
Android:Display time after adding GMT time zone
(2 answers)
Closed 4 years ago.
I am converting milliseconds to the time of the respective country time format, for example, pakistan, US etc
For example
timeinmilliseconds=1549362600000
So its respective Time formate from which I got these milliseconds is 15:30 or 3:30 in 12 hr format
When I want to convert these milliseconds back to that time
I get 10:30 (Five hrs back)
public String getTimeFromLong(long timeInMilliseconds){
String mytime="";
long minute = (timeInMilliseconds / (1000 * 60)) % 60;
long hour = (timeInMilliseconds / (1000 * 60 * 60)) % 24;
mytime = String.format("%02d:%02d", hour, minute);
return mytime;
}
If I select time 4:00
I converted to that to milliseconds (This part is OK)
And wants the time back from milliseconds but get five hours back
For example, If I select time 9:30
convert it to milliseconds and then to time
I get 4:30
You need to use your local time zone to get the time in your region, the default is being apllied which is the Greenwich Mean Time (GMT). For Pakistan use Asia/Karachi like so:
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("hh:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Karachi"));
Use this method to convert milliseconds into your local time
public String getTime(long time){
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(time);
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date date = new Date(time);
String kTime = format.format(date);
return kTime;
}
Using Java 8 we can do the following.
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
to get date and time
Use below code to get time from long values:
public String getTimeFromLong(long timeInMilliseconds){
// Creating date format
DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date result = new Date(timeInMilliseconds);
return simple.format(result);
}
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)
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 number representing the number of nanoseconds since 12:00 a.m., January 1, 1904, universal time. I wish to instantiate a java.util.Date object representing that date. How should I proceed?
You first need to convert your number representing nanoseconds to milliseconds.
Then for the given date string, get the total number of milliseconds since the unix time Epoch, and then add the number earlier converted to milliseconds to it.
Here's the working code:
String target = "1904/01/01 12:00 AM"; // Your given date string
long nanoseconds = ...; // nanoseconds since target time that you want to convert to java.util.Date
long millis = TimeUnit.MILLISECONDS.convert(nanoseconds, TimeUnit.NANOSECONDS);
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm aaa");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(target);
long newTimeInmillis = date.getTime() + millis;
Date date2 = new Date(newTimeInmillis);
System.out.println(date2);
Add an import java.util.concurrent.TimeUnit;.
I think it is trivial:
final GregorianCalendar startDate = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
startDate.clear();
startDate.set(1904, Calendar.JANUARY, 1);
final long startMillis = startDate.getTimeInMillis();
new Date(nanos / 1000 / 1000 + startMillis)
Date date = new Date(new Date().getTime()-(time in nanoseconds/(1000*1000)));
what's wrong in using this? I tested with a value of "time in nanoseconds" for June 8th 1926 and it works. and date format has nothing to do with it, the underlying milliseconds value representing the time is what is required.
First of all java.util.Date
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
So, if you have variable milliseconds
Somehow calculate number of milliseconds between your date and Jan 1, 1970 (Unix epoch) diff
Use Date(long) constructor
new Date(milliseconds - diff);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating difference in dates in Java
How do you subtract Dates in Java?
I am parsing two dates from a string that look like:
Oct 15, 2012 1:07:13 PM
Oct 23, 2012 03:43:34 PM
What I need to do is find the difference between these two dates, ex:
Oct 23, 2012 03:43:34 PM - Oct 15, 2012 1:07:13 PM
= 8 days 2 hours 36 minutes 21 seconds
^ This is what I need to get with the two date/times I have
I believe I need to parse the format and convert it to another format, then subtract the difference between and do the math to get the days/hours/minutes/seconds between
In contrary to what other answerers try to imply, calculating the difference between two dates isn't that trivial in standard Java SE.
Your first step is indeed to convert those strings to useable Date instances. You can do this using SimpleDateFormat. Here's a kickoff example:
String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";
SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.ENGLISH);
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
(please note the importance of the optional Locale argument here, this is often overlooked in answers about converting strings to dates)
Your next step is calculating the difference between those 2 dates. This is a terrible job when you are restricted to the standard Java SE API. Best what you can get is the java.util.Calendar.
Note that you could of course substract the milliseconds and calculate the difference using the usual arithmetic operators.
long differenceInMillis = date2.getTime() - date1.getTime();
// ...
But this naive approach doesn't take leap years into account, let alone daylight saving time and local-specific changes in datetime.
As to the java.util.Calendar approach, you basically need to use Calendar#add() in a counter loop to get the elapsed value for years, months and days. This takes leap years, daylight saving time and local-specific disturbances in time properly into account.
First create this helper method to eliminate some boilerplate code:
public static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
Now you can calculate the elapsed time as follows:
Calendar start = Calendar.getInstance();
start.setTime(date1);
Calendar end = Calendar.getInstance();
end.setTime(date2);
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone(); // Otherwise changes are been reflected.
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
System.out.format("%d years, %d months, %d days, %d hours, %d minutes, %d seconds", elapsed);
Pretty ugly, yeah.
If you going to work with date and time in Java pretty often, then you may find Joda time the walhalla. Here's a concrete kickoff example of how you could do it all with pure Joda Time:
String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";
DateTimeFormatter dtf = DateTimeFormat.forPattern("MMM d, yyyy h:mm:ss a").withLocale(Locale.ENGLISH);
DateTime dateTime1 = dtf.parseDateTime(string1);
DateTime dateTime2 = dtf.parseDateTime(string2);
Period period = new Period(dateTime1, dateTime2);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" years ")
.appendMonths().appendSuffix(" months ")
.appendWeeks().appendSuffix(" weeks ")
.appendDays().appendSuffix(" days ")
.appendHours().appendSuffix(" hours ")
.appendMinutes().appendSuffix(" minutes ")
.appendSeconds().appendSuffix(" seconds ")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed);
Much better, right? The plural "s" needs some work though, but that's beyond the question.
You need to use SimpleDateFormat to parse String and create Date
Then you can find the difference between dates.
Here is javadoc for SimpleDateFormat
try this:
Calendar ca1 = Calendar.getInstance();
ca1.set(2012,05,25);
// Addition of date in java
ca1.add(Calendar.DATE, 23); // Add 23 days in Dates in Calendar
ca1.add(Calendar.MONTH, 2); // Add 2 Month in Date in Calendar
ca1.add(Calendar.YEAR, 4); // add 4 Year in Date in Calendar
ca1.add(Calendar.DATE, -23); // sub 23 days in Dates in Calendar
ca1.add(Calendar.MONTH, -2); // sub 2 Month in Date in Calendar
ca1.add(Calendar.YEAR, -4); // sub 4 Year in Date in Calendar
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.