How to add minutes to a time stamp that I already have? - java

I searched a lot, but I found a way to add or subtract time from the calendar instance which gives the current time.. how do I subtract time from the last modified time of a given file?
UPDATE :
I've been using Java1.4. That is the reason I'm unable to find any methods to do this.
I extracted the modified date as a string. I wanted to convert this string obey I a calendar object so that it's easier for me to apply add () of the calendar object to the time. I've been facing issues with the same. is this approach correct? Could you please assist

NIO and java.time
Path filePath = Paths.get("myFile.txt");
Duration timeToSubtract = Duration.ofMinutes(7);
FileTime lastModified = Files.getLastModifiedTime(filePath);
Instant lastModifiedInstant = lastModified.toInstant();
Instant timeBeforeLastModified = lastModifiedInstant.minus(timeToSubtract);
System.out.println("Time after subtraction is " + timeBeforeLastModified);
Running just now on my computer I got this output:
Time after subtraction is 2017-02-18T03:06:04Z
The Z at the end indicates UTC. Instant::toString (implicitly called when appending the Instant to a string) always generates a string in UTC.
I am using the modern Java NIO API and java.time, the modern Java date and time API. NIO gives us a FileTime in this case denoting the time the file was last modified. In order to do our time math I first convert it to an Instant, which is a central class of java.time. The minus method of an Instant subtracts a Duration, an amount of time, and returns a new Instant object.
Don’t use Calendar. That class was poorly designed and is long outdated.
Link: Oracle tutorial: Date Time explaining how to use java.time.

If you dont have to use calendar, than just use the new Java DateTime API available since Java8 https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
There you have very nice convenience methods like plus/minus etc.
For example you can simply write
LocalTime now = LocalTime.now();
now.minusHours(2);

Timestamp (as long) you can set in Calendar instance. And after that you can add() time.
public void time() {
long timeStamp = 31415926535L;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);
// Substract 1 hour
calendar.add(Calendar.HOUR, -1);
// Add 20 minutes
calendar.add(Calendar.MINUTE, 20);
}

You can use setTime() like this:
yourTimeStamp.setTime(yourTimeStamp.getTime() + TimeUnit.MINUTES.toMillis(minutesToAdd));

Since Java 8, java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy. So I edit my codes, remove the legacy classes.
Thanks #Ole V.V. and #Basil Bourque for pointing my problems.
I'm confused about your issue. I guess you want to modify a file's last modified time.
So I write down the codes.
import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Test {
private static final long ONE_SECOND = 1000L;
private static final long ONE_MINUTE = 60L * ONE_SECOND;
public static void main(String[] args) {
File file = new File("test.txt");
if (!file.exists()) {
System.err.println("File doesn't exist.");
return;
}
//get file's last modified, in millisecond
long timestamp = file.lastModified();
System.out.println("File's last modified in millisecond: " + timestamp);
//print time for human, convert to LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
System.out.println("File's last modified in LocalDateTime: " + localDateTime);
//add a minute
timestamp = timestamp + ONE_MINUTE;
//modify file's last modified
boolean isModified = file.setLastModified(timestamp);
if (isModified) {
System.out.println("Update file's last modified successfully.");
System.out.println("File's last modified in millisecond: " + file.lastModified());
//print time for human, convert to LocalDateTime
System.out.println("File's last modified in LocalDateTime: " +
LocalDateTime.ofInstant(Instant.ofEpochMilli(file.lastModified()), ZoneId.systemDefault()));
} else {
System.err.println("Update file's last modified failed.");
}
}
}
Besides, If you want modify a timestamp, just use +/- operations.
And you can convert timestamp to LocalDateTime, and use LocalDateTime's api to modify time easily.
public void modifyTime() {
//modify timestamp: add one second
long timestamp = System.currentTimeMillis();
timestamp = timestamp + 1000L;
//convert timestamp to LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
//modify LocalDateTime
//add a minute
localDateTime = localDateTime.plusMinutes(1);
//subtract a second
localDateTime = localDateTime.minusSeconds(1);
}
If I misunderstood your idea, please let me know.

Related

How to compare two dates and how to check if our present date is 3 days before a checkpoint [duplicate]

I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.
The function needs to be compliant with these restrictions:
Prevent errors from date savetime
Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)
If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);
If you want literal 24 hour days, (a duration), you can use the Duration class instead:
LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option
For more information, refer to this document.
Based on VGR's comments here is what you can use:
ChronoUnit.DAYS.between(firstDate, secondDate)
You can use until:
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);
System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));
Output:
Until christmas: P5M21D
Until christmas (with crono): 174
As mentioned in a comment, if no unit is specified until returns Period.
Snippet from the documentation:
A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.
DAYS.between
You can use DAYS.between from java.time.temporal.ChronoUnit
e.g.
import java.time.temporal.ChronoUnit;
...
long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);
If startDate and endDate are instance of java.util.Date
We can use the between( ) method from ChronoUnit enum:
public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
//..
}
ChronoUnit.DAYS count days which completed 24 hours.
import java.time.temporal.ChronoUnit;
ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());
//OR
ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));
Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).
The docs for both actually mention both approaches and say to use whichever one is more readable.
Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :
Output :
*Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368.
**Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*
package com.bitiknow.date;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/**
*
* #author pradeep
*
*/
public class LocalDateTimeTry {
public static void main(String[] args) {
// Date in String format.
String dateString = "2015-03-01";
// Converting date to Java8 Local date
LocalDate startDate = LocalDate.parse(dateString);
LocalDate endtDate = LocalDate.now();
// Range = End date - Start date
Long range = ChronoUnit.DAYS.between(startDate, endtDate);
System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
+ " is ==> " + range);
range = ChronoUnit.DAYS.between(endtDate, startDate);
System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
+ " is ==> " + range);
}
}
Get number of days before Christmas from current day , try this
System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));
Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 month to the current date
LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + date2);
// Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
long daysNegative = ChronoUnit.DAYS.between(date2, today);
System.out.println("Days : "+daysNegative);
// Put old date 1st and new date 2nd in 'between' method to get +ve date difference
long datePositive = ChronoUnit.DAYS.between(today, date2);
System.out.println("Days : "+datePositive);
}
}
get days between two dates date is instance of java.util.Date
public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
}
If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -
public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
// Check for null values here
return endDate.toEpochDay() - startDate.toEpochDay();
}
I know this question is for Java 8, but with Java 9 you could use:
public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}
Use the class or method that best meets your needs:
the Duration class,
Period class,
or the ChronoUnit.between method.
A Duration measures an amount of time using time-based values (seconds, nanoseconds).
A Period uses date-based values (years, months, days).
The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.
https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate dateBefore = LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
System.out.println(daysBetween);

Retrieving a DateTime Using resultset into a DateTime field [duplicate]

I'm retrieving a timestamp object from a database using ResultSet.getTimestamp(), but I'd like an easy way to get the date in the format of MM/DD/YYYY and the time in a format of HH:MM xx. I was tinkering around, it it looks as though I can do such by making use of the Date and/or DateTime objects within Java. Is that the best way to go, or do I even need to convert the timestamp to accomplish this? Any recommendations would be helpful.
....
while(resultSet.next()) {
Timestamp dtStart = resultSet.getTimestamp("dtStart");
Timestamp dtEnd = resultSet.getTimestamp("dtEnd");
// I would like to then have the date and time
// converted into the formats mentioned...
....
}
....
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.
java.time
Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.
For your work we need a time zone and a couple of formatters. We may as well declare them static:
static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
Now the code could be for example:
while(resultSet.next()) {
ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
.atZoneSameInstant(zone);
// I would like to then have the date and time
// converted into the formats mentioned...
String dateFormatted = dtStart.format(dateFormatter);
String timeFormatted = dtStart.format(timeFormatter);
System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
}
Example output (using the time your question was asked):
Date: 09/20/2011; time: 18:13 -0400
In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.
If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:
ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
.atZone(zone);
No matter the details I trust you to do similarly for dtEnd.
I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();
Converts this Timestamp object to a code LocalDateTime.
The conversion creates a code LocalDateTime that represents the
same year, month, day of month, hours, minutes, seconds and nanos
date-time value as this code Timestamp in the local time zone.
since 1.8

TimeZone with Calendar confusing results

I have been working with timezone conversions lately and am quite astonished by the result i get.Basically, i want to convert a date from one timezone into another. below is the code, conversions working fine, but what i have observed while debugging is, the date is not converted unless i call Calendar#get(Calendar.FIELD).
private static void convertTimeZone(String date, String time, TimeZone fromTimezone, TimeZone toTimeZone){
Calendar cal = Calendar.getInstance(fromTimezone);
String[] dateSplit = null;
String[] timeSplit = null;
if(time !=null){
timeSplit = time.split(":");
}
if(date!=null){
dateSplit = date.split("/");
}
if(dateSplit !=null){
cal.set(Calendar.DATE, Integer.parseInt(dateSplit[0]));
cal.set(Calendar.MONTH, Integer.parseInt(dateSplit[1])-1);
cal.set(Calendar.YEAR, Integer.parseInt(dateSplit[2]));
}
if(timeSplit !=null){
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1]));
}
// System.out.println("Time in " + fromTimezone.getDisplayName() + " : " + cal.get(Calendar.DATE) +"/"+ (cal.get(Calendar.MONTH)+1)+"/"+ cal.get(Calendar.YEAR) +" " + ((cal.get(Calendar.HOUR_OF_DAY)<10) ? ("0"+cal.get(Calendar.HOUR_OF_DAY) ): (cal.get(Calendar.HOUR_OF_DAY)))
// +":" + (cal.get(Calendar.MINUTE)<10 ? "0"+cal.get(Calendar.MINUTE) : cal.get(Calendar.MINUTE)) );
cal.setTimeZone(toTimeZone);
System.out.println("Time in " + toTimeZone.getDisplayName() + " : " + cal.get(Calendar.DATE) +"/"+ (cal.get(Calendar.MONTH)+1)+"/"+ cal.get(Calendar.YEAR) +" " + ((cal.get(Calendar.HOUR_OF_DAY)<10) ? ("0"+cal.get(Calendar.HOUR_OF_DAY) ): (cal.get(Calendar.HOUR_OF_DAY)))
+":" + (cal.get(Calendar.MINUTE)<10 ? "0"+cal.get(Calendar.MINUTE) : cal.get(Calendar.MINUTE)) );
}
public static void main(String[] args) throws ParseException {
convertTimeZone("23/04/2013", "23:00", TimeZone.getTimeZone("EST5EDT"), TimeZone.getTimeZone("GB"));
}
Expected Output: Time in Greenwich Mean Time : 24/4/2013 04:00
Output i got when i comment sysout 1: Time in Greenwich Mean Time : 23/4/2013 23:00
If i un-comment sysout1 i get the expected valid output.
Any help is appreciated
The internal representation of the given date is not evaluated until really needed, that is until you try to access it by those getters. However the best way of parsing dates is through SimpleDateFormat.
EDIT (added for summarize the comments below and to better clarify my answer).
Calendar works this way for better efficiency: instead of recalculate everithing each time you call a setter, it waits until you call a getter.
Calendar should be used mainly for date calculations (see add() and roll()), but you are using it for parsing and formatting: these tasks are better accomplished with SimpleDateFormat, that's why I say that your usage of Calendar is not elegant.
See this example:
private static void convertTimeZone(String date, String time,
TimeZone fromTimezone, TimeZone toTimeZone) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
df.setTimeZone(fromTimezone);
Date d = df.parse(date + " " + time);
df.setTimeZone(toTimeZone);
System.out.println("Time in " + toTimeZone.getDisplayName() + " : " +
df.format(d));
}
I have reimplemented your method using SimpleDateFormat only. My method is smaller, there is no splitting logic (it's hidden in parse()), and also the output is handled in a simpler way. Furthermore the date format is expressed in a compact and standard way that can be easily internationalized using a ResourceBundle.
Also note that the timezone conversion is just a formatting task: the internal representation of the parsed date does not change.
The answer is partly explained in a commented section in setTimeZone():
Consider the sequence of calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
generally, a call to setTimeZone() affects calls to set() BEFORE AND
AFTER it up to the next call to complete().
In other words, the sequence
Set Calendar time
Change TimeZone
is interpreted to mean "Use this time in this new time zone", while the sequence
Set Calendar time
Get the time (or some part of it)
Change Time Zone
will be interpreted as "Use this time in the old time zone, then change it".
So, in your case, to get the behavior you are hoping for, you will need to call get(), or any other method that internally calls complete() inside the Calendar, before you change the time zone.
Are you restricted to using TimeZone and Calendar? If not I suggest using the excellent Library JodaTime which makes handling time zones much easier.
Your example would then look like this:
public static void convertTimeZoneJoda(String date, String time, DateTimeZone fromTimezone, DateTimeZone toTimeZone) {
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/yyyyHH:mm").withZone(fromTimezone);
DateTime dt = dtf.parseDateTime(date+time).withZone(toTimeZone);
System.out.println("Time in " + toTimeZone.getID() + " : " + dt.toString());
}
public static void main(String[] args) {
convertTimeZoneJoda("23/04/2013", "23:00", DateTimeZone.forID("EST5EDT"), DateTimeZone.forID("GMT"));
}
JodaTime also allows for convenient conversation between TimeZone and DateTimeZone.
To add to #Pino's answer, the reason why get() doesn't return an updated time is because setTimeZone() simply doesn't update the fields, just sets areAllFieldsSet to false, which is useless since get() doesn't check for it. If you ask me, this is very poorly coded from SUN's part. Here is the competent code from Calendar:
setTimeZone():
public void setTimeZone(TimeZone value){
zone = value;
sharedZone = false;
areAllFieldsSet = areFieldsSet = false;
}
get():
protected final int internalGet(int field){
return fields[field];
}
This code works for me to convert to UTC:
create a Calendar Object with UTC time zone
Calendar utcTime = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
set the point in time in the UTC Calendar object from the "any time zone" Calendar object
utcTime.setTimeInMillis(myCalendarObjectInSomeOtherTimeZone.getTimeInMillis());
utcTime will now contain the same point in time as myCalendarObjectInSomeOtherTimeZone converted to UTC.

How to convert HH:mm:ss.SSS to milliseconds?

I have a String 00:01:30.500 which is equivalent to 90500 milliseconds. I tried using SimpleDateFormat which give milliseconds including current date. I just need that String representation to milliseconds. Do I have to write custom method, which will split and calculate milliseconds? or Is there any other way to do this? Thanks.
I have tried as follows:
String startAfter = "00:01:30.555";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = dateFormat.parse(startAfter);
System.out.println(date.getTime());
You can use SimpleDateFormat to do it. You just have to know 2 things.
All dates are internally represented in UTC
.getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
package se.wederbrand.milliseconds;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "00:01:30.500";
Date date = sdf.parse("1970-01-01 " + inputString);
System.out.println("in milliseconds: " + date.getTime());
}
}
If you want to parse the format yourself you could do it easily with a regex such as
private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
public static long dateParseRegExp(String period) {
Matcher matcher = pattern.matcher(period);
if (matcher.matches()) {
return Long.parseLong(matcher.group(1)) * 3600000L
+ Long.parseLong(matcher.group(2)) * 60000
+ Long.parseLong(matcher.group(3)) * 1000
+ Long.parseLong(matcher.group(4));
} else {
throw new IllegalArgumentException("Invalid format " + period);
}
}
However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
If you want to use SimpleDateFormat, you could write:
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
{ sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
private long parseTimeToMillis(final String time) throws ParseException
{ return sdf.parse("1970-01-01 " + time).getTime(); }
But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)
Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)
Personally, I'd probably write a custom method.
I am presenting two options:
Time4J, an advanced external date, time and time interval library.
java.time, the built-in modern Java date and time API.
SimpleDateFormat and Date are the wrong classes to use, both because a duration of 1 minute 30.5 seoncds is not a date and because those classes have long gone out of any reasonable use.
Time4J
This is the elegant solution. We first declare a formatter:
private static final Duration.Formatter<ClockUnit> DURATION_FORMAT
= Duration.formatter(ClockUnit.class, "hh:mm:ss.fff");
Then parse and convert to milliseconds like this:
String startAfter = "00:01:30.555";
Duration<ClockUnit> dur = DURATION_FORMAT.parse(startAfter);
long milliseconds = dur.with(ClockUnit.MILLIS.only())
.getPartialAmount(ClockUnit.MILLIS);
System.out.format("%d milliseconds%n", milliseconds);
Output is:
90555 milliseconds
java.time
The java.time.Duration class can only parse ISO 8601 format. So I am first converting your string to that format. It goes like PT00H01M30.555S (the leading zeroes are not required, but why should I bother removing them?)
String startAfter = "00:01:30.555";
String iso = startAfter.replaceFirst(
"^(\\d{2}):(\\d{2}):(\\d{2}\\.\\d{3})$", "PT$1H$2M$3S");
Duration dur = Duration.parse(iso);
long milliseconds = dur.toMillis();
System.out.format("%d milliseconds%n", milliseconds);
Output is the same as before:
90555 milliseconds
Another difference from Time4J is that the Java Duration can be directly converted to milliseconds without being converted to a Duration of only milliseconds first.
Links
Time4J - Advanced Date, Time, Zone and Interval Library for Java
Oracle tutorial: Date Time explaining how to use java.time.

Unix epoch time to Java Date object

I have a string containing the UNIX Epoch time, and I need to convert it to a Java Date object.
String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
Date expiry = df.parse(date);
} catch (ParseException ex) {
ex.getStackTrace();
}
The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat().
How about just:
Date expiry = new Date(Long.parseLong(date));
EDIT: as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:
Date expiry = new Date(Long.parseLong(date) * 1000);
Epoch is the number of seconds since Jan 1, 1970..
So:
String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );
For more information:
http://www.epochconverter.com/
java.time
Using the java.time framework built into Java 8 and later.
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]
In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.
ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
long timestamp = Long.parseLong(date)
Date expiry = new Date(timestamp * 1000)
Better yet, use JodaTime. Much easier to parse strings and into strings. Is thread safe as well. Worth the time it will take you to implement it.
To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.
long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)
Hum.... if I am not mistaken, the UNIX Epoch time is actually the same thing as
System.currentTimeMillis()
So writing
try {
Date expiry = new Date(Long.parseLong(date));
}
catch(NumberFormatException e) {
// ...
}
should work (and be much faster that date parsing)

Categories