i have this code, i need show only hours:min:sec, any help?
String var = "1429174464829"; (this is time in System.currentTimeMillis() )
String p = "HH:mm:ss";
SimpleDateFormat f = new SimpleDateFormat(p);
long t = var - System.currentTimeMillis();
String result = f.format(new Date(t));
in example String var, is 1 hours higher than System.currentTimeMillis()
result problem
EDIT: i obtain: result = 21:59:00
thanks
Java 8
Okay, this is a little unpleasant, but will get the job done, this is using Java 8's Time API
LocalDateTime dt1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(1429174464829L), ZoneId.systemDefault());
LocalDateTime dt2 = LocalDateTime.now().plusDays(1);
System.out.println(dt1);
System.out.println(dt2);
StringJoiner sj = new StringJoiner(":");
long hours = ChronoUnit.HOURS.between(dt1, dt2);
sj.add(Long.toString(hours));
dt2 = dt2.minusHours(hours);
long mins = ChronoUnit.MINUTES.between(dt1, dt2);
sj.add(Long.toString(mins));
dt2 = dt2.minusMinutes(mins);
long secs = ChronoUnit.SECONDS.between(dt1, dt2);
sj.add(Long.toString(secs));
System.out.println(sj);
And will output something like...
2015-04-16T18:54:24.829
2015-04-17T14:10:54.281
19:16:29
Now, if I was to do something like...
LocalDateTime dt2 = LocalDateTime.now().plusDays(4);
I'd get 91:21:10 instead.
I'm hoping someone has a better solution, cause that's kind of a mess...
Joda-Time
If you can't use Java 8, then use Joda-Time
DateTime dt1 = new DateTime(1429174464829L);
DateTime dt2 = DateTime.now().plusDays(4);
System.out.println(dt1);
System.out.println(dt2);
Duration yourDuration = new Duration(dt1, dt2);
Period period = yourDuration.toPeriod();
PeriodFormatter hms = new PeriodFormatterBuilder()
.printZeroAlways()
.appendHours()
.appendSeparator(":")
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
String result = hms.print(period);
System.out.println(result);
Which outputs 91:26:33
There is some time zone issue. we have to specify time zone with SimpleDateFormat. It gives result after adding time difference of your system time zone with standard UTC time zone. By default it takes your local system time zone.
String var = "1429174464829"; (this is time in System.currentTimeMillis() )
String p = "HH:mm:ss";
SimpleDateFormat f = new SimpleDateFormat(p);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
long t = long.parseLong(var) - System.currentTimeMillis();
String result = f.format(new Date(t));
Well, in my experience this kind of thing is something you don't want to code yourself. Somewhere down the line you'll run into border cases like Daylight Saving Time, Leap years, etc, etc.
If you want to do this kind of thing reliably, use a time library like JodaTime (my preference)
For instance, the Period class can give you individual parts, and can be produced form a Duration by calling toPeriod().
I think you can use Jodatime for getting hours and its a good library. Hope it helps. Cheers!
Related
I have a String contains date and time like below :
String test = ""20220215160000Z-0400";
The correct value that I need to print out is :
Date = 02/15/2022
Time = 12:00
The time is basically the 16:00 - 4 hours in the offset. I couldn't figure out how to do it. Any helps will be appreciated. Currently, my codes is like below :
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
Date parsedDate = dateFormat.parse(test);
Timestamp timeStamp = new Timestamp(parsedDate.getTime());
System.out.println(timeStamp.toString());
And the print out is : 2022-02-15 16:00:00.0
I need the value to be 2022-02-15 12:00:00.0
using java.time api(you can change it to java easily):
var str = "20220215160000Z-0400"
var formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'Z")
var zonedDate = ZonedDateTime.parse(str, formatter)
println(zonedDate.offset)
var offsetTime = zonedDate.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.of("-0800"))
var for2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
println(for2.format(offsetTime))
notice i'm using ZoneOffset.of("-0800") instead of ZoneOffset.of("-0000")
Your date format is quite strange: as it does not reflect local time but UTC time, "20220215160000Z-0400" is normally regarded as local time (UTC-4) = 1600 HRS, but based on your explanation you'd like it such that UTC time = 1600 HRS, and therefore local time is 1200 HRS.
This means you need to have a "fix" on the date. See the sample code below:
String test = "20220215160000Z-0400";
ZoneId desiredZone = ZoneOffset.of("-0400");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'Z");
LocalDateTime localDateTime = LocalDateTime.parse(test, formatter);
ZonedDateTime min4HrsZonedDateTime = ZonedDateTime.of(localDateTime, desiredZone);
ZonedDateTime min4HrsZonedDateTimeFix = min4HrsZonedDateTime.withZoneSameLocal(ZoneOffset.UTC).withZoneSameInstant(desiredZone);
System.out.println("timestamp = " +Timestamp.from(min4HrsZonedDateTimeFix.withZoneSameLocal(ZoneOffset.systemDefault()).toInstant()));
I converted the time back to UTC but without using timezone, hence the min4HrsZonedDateTimeFix
I have two strings which can be seen as time stamps:
String min="2017-04-15 13:27:31";
String max="2017-04-15 13:40:01";
Assume we want to find out the time passed from first time stamp to the second one. If there was only the time and no date included, I could get it using my following code:
String[] partsMin=min.split(":");
String[] partMax=max.split(":");
int diffZero=Integer.parseInt(partMax[0])-Integer.parseInt(partsMin[0]);
int diffOne=Integer.parseInt(partMax[1])-Integer.parseInt(partsMin[1]);
int diffOTwo=Integer.parseInt(partMax[2])-Integer.parseInt(partsMin[2]);
diffInSec=diffZero*3600+diffOne*60+diffOTwo;
So here is the question. How to get the job done while there is a date within the time stamp?
I would construct LocalDateTime instances from it.
Then i would get the milliseconds from it and substract startTime from EndTime.
What is remaining are the milliseconds passed between the two. A DateTimeFormatter is helpful as well for this purpose.
String strMin = "2017-04-15 13:27:31";
DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(strMin, formatter);
String strMax = "2017-04-15 13:40:01";
LocalDateTime dateTimeMax = LocalDateTime.parse(strMax, formatter);
long minutes = ChronoUnit.MINUTES.between(dateMin, dateMaxto);
long hours = ChronoUnit.HOURS.between(dateMin, dateMax);
If you want to get the milliseconds:
long millisPassed = dateMax.toEpochMilli() - dateMax.toEpochMilli();
Use the java date time libraries (even the old Date class would be fine for this) to parse the string into a proper object.
Depending on the date time library you chose you can then look at the difference between them. The simplest would be something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = sdf.parse(str1);
Date date2 = sdf.parse(str2);
long differenceInSeconds = (date2.getTime()-date1.getTime())/1000;
The new Java 8 time classes would also allow you to do this and would be better to learn going forwards. I can't remember the syntax for that off the top of my head though.
Did you try with replace all the other part of your String like this :
String[] partsMin = min.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
String[] partMax = max.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
Doing this in your code:
int diffZero=Integer.parseInt(partMax[0])
is the same as doing:
int diffZero=Integer.parseInt("2017-04-15")
that is generating an Exception(NumberFormatException)
you should better try to PARSE those strings min and max into a date
Edit:
you can inspect your code/ variables: and see that splitting to ":" is not giving you back the correct array since the element at index 0 is holding more information than you need...
but as I said before, you are going on the wrong path, dont re invent the wheel and look how practical will get using the APIs that java has for us:
String min = "2017-04-15 13:27:31";
String max = "2017-04-15 13:40:01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(min, formatter);
LocalDateTime dateTimeMax = LocalDateTime.parse(max, formatter);
long days = ChronoUnit.DAYS.between(dateTimeMin, dateTimeMax);
long minutes = ChronoUnit.MINUTES.between(dateTimeMin, dateTimeMax);
System.out.println(days);
System.out.println(minutes);
use SimpleDateFormat to parse the date string, and do operation on Date result, you will get right value. This works well for date between '2017-02-28 23:59:59' and '2017-03-01 00:00:01'
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = format.parse("2017-02-28 23:59:59");
Date date2 = format.parse("2017-03-01 00:00:01");
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff = time2 - time2; // should be 2000
I want to find out difference in milliseconds between next occuring 3PM new york time and current time. i.e. if it is 5 pm NY time right now. I should get the difference between 5pm now and 3pm NY time next day. How can I do it in Java ? I am happy using JodaTime also, may you please give an exmaple, how this can be done.
Please help.
Here are three solutions using the most prevalent library choices. They all follow the same pattern, just using the nomenclature of the given libraries.
Joda solution:
DateTime dt = new DateTime(DateTimeZone.forID("US/Eastern"));
DateTime target = dt
.withHourOfDay(15)
.withMinuteOfHour(0)
.withSecondOfMinute(0)
.withMillisOfSecond(0);
if (target.isBefore(dt)) {
target = target.plusDays(1);
}
System.out.println(target.getMillis() - dt.getMillis());
Java 8 solution
Got to love that until() method:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Eastern"));
ZonedDateTime target2 = zdt
.withHour(15)
.withMinute(0)
.withSecond(0)
.withNano(0);
if (target2.isBefore(zdt)) {
zdt = zdt.plusDays(1);
}
System.out.println(zdt.until(target2, ChronoUnit.MILLIS));
Java <=7 solution
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
Calendar target3 = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
target3.set(Calendar.HOUR_OF_DAY, 15);
target3.set(Calendar.MINUTE, 0);
target3.set(Calendar.SECOND, 0);
target3.set(Calendar.MILLISECOND, 0);
if (target3.before(c)) {
target3.add(Calendar.DATE, 1);
}
System.out.println(target3.getTimeInMillis() - c.getTimeInMillis());
How about this?
Date now = new Date();
Calendar ny3pmCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
ny3pmCalendar.setTime(now);
if(ny3pmCalendar.get(Calendar.HOUR_OF_DAY) >= 15) {
// next day
ny3pmCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
ny3pmCalendar.set(Calendar.HOUR, 15);
ny3pmCalendar.set(Calendar.MINUTE, 0);
ny3pmCalendar.set(Calendar.SECOND, 0);
ny3pmCalendar.set(Calendar.MILLISECOND, 0);
long diff = ny3pmCalendar.getTimeInMillis() - now.getTime();
System.out.println(diff);
try joda DateTime and Period
Date oldDate = new Date();
DateTime old = new DateTime(oldDate);
DateTime now = new DateTime();
Period period = new Period(old, now, PeriodType.yearMonthDayTime());
period.getYears();// give the difference in year
period.getMonths();
period.getDays();
period.getMinutes();
period.getSeconds();
Joda Time - Its having lots of features for date time manipulation
I'm trying to get a time string in the format of YYYYMMDD-HHMMSSMilliseconds in Android
Ex: 20130312-1723437520 (2013 March 12th, 17 Hour 23 Minutes 43 Seconds 7520 Milliseconds)
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("yyyyMMdd-HHmmss");
First of all, above code doesn't even work properly. snapshotTime is always set to the format string itself.
Second of all, according to the Android documentation, there's no way to record milliseconds.
How can I accomplish this?
See the SimpleDateFormat class, you can format a Date object into the required format (upper-case S will give millis)
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String str = fmt.format(now);
That said, using Joda Time is usually a good idea (Proguard will strip code you don't use).
You'll have to use the strftime formatting, as noted in the Android docs.
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("%Y%m%d-%H%M%S");
If you really want to use milliseconds than I would recommend SimpleDateFormat.
Try getting the time as unix timestamp with milliseconds from
long currentTime = System.currentTimeMillis();
or convert your time to milliseconds:
long currentTime = now.toMillis(true);
Then you can convert this to your desired date:
Time now = new Time();
now.set(currentTime);
String snapshotTime = now.format("%Y%m%d-%H%M%S")+""+(currentTime%1000);
Didn't test it but hope it works :)
I would recommend to use this little library, it's very helpful when working with dates. Have a look at the DateTimeFormatter class.
As an alternative use Calendar and SimpleDateFormater (you'll have to adjust the format string of course, see this for explanation of the symbols)
Calendar c = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-SSSS");
String date = sdf.format(c.getTime());
You can try this:
public static String format() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
Date now = new Date();
return simpleDateFormat.format(now);
}
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.