FAQ Database Discussion Community


Coverting String to LocalTime with/without nanoOfSeconds

java,java-8,formatter,java-time,localtime
I need to convert a string to LocalTime (java-8 not joda) that may or maynot have nanoOfSeconds in the string. The String format is in the form of 07:06:05 or 07:06:05.123456 The string may or may not have a decimal place in the seconds and when it does there could...

How to get next MonthDay (next Christmas) with java 8 time API?

time,java-8,java-time
Let's say I want to know how many days are until Christmas with a method that works any day of any year so next Christmas may be this year or next year that I don't know if it is a leap year or not. I might calculate the next Christmas...

How to use properly DateTimeFormatter / convert from java.time.Instant [duplicate]

java-8,jodatime,jsp-tags,java-time,jsr310
This question already has an answer here: How to covert Joda-Time's DateTimeFormat.forStyle() to JSR 310 JavaTime? 2 answers Ok, I need some help to understand how to use the java.time formatters. I keep crashing on "Unsupported field" exceptions all day (pun not intended, sorry). Just some examples. This is...

JSON Java 8 LocalDateTime format in Spring Boot

java,json,java-8,spring-boot,java-time
I'm having a small problem with formatting a Java 8 LocalDateTime in my Spring Boot Application. With 'normal' dates I have no problem, but the LocalDateTime fields are converted to the following: "startDate" : { "year" : 2010, "month" : "JANUARY", "dayOfMonth" : 1, "dayOfWeek" : "FRIDAY", "dayOfYear" : 1,...

Joda betweenDays (LocalDate,LocalDate) not applicable

java,datetime,jodatime,java-time
I am having trouble using Joda daysBetween function. It keeps telling me The method daysBetween(ReadableInstant, ReadableInstant) in the type Days is not applicable for the arguments (LocalDate, LocalDate) when I try to insert two localdate items. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH); LocalDate date = LocalDate.parse(reviewDate, formatter); Date dateNow...

Bug in java.time.Duration

java,java-8,java-time
I need to parse Durations from strings. Java 8 provide a method for that taking the ISO-8601 standard as a basis: Duration.parse("p10d"); // parses as ten days Duration.parse("pt1h"); // parses as one hour As the standard states that "it is permitted to omit the 'T' character by mutual agreement" some...

What is the difference of using TemporalAmount or TemporalUnit in Java 8?

java,datetime,java-8,java-time
I write some piece of code in Java 8 which use time arithmetic. I realize that I can implement in differentways. Lets look at simple code below. Of course it is the same result but I confused which way is mostly applied or most efficient to make arithmetic operations in...

Can I use the new java 8 time API within a scala Play 2.3.8 project?

scala,playframework,java-8,java-time
I thought that this was feasible by setting the java version to 1.8 (java.runtime.version=1.8 inside system.properties file). But when I tried to compile the project using activator compile I got all kinds of not found: type LocalDateTime errors. Am I doing something wrong (configuration-wise)? Is there any way to overcome...

Java8 LocalDateTime to XMLGregorianCalender Remove “+05:30” Portion

java-8,java-time
Did like below, LocalDateTime currentUTCTime = LocalDateTime.now(ZoneId.of("UTC")); String reqPattern = currentUTCTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS")); System.out.println("Required pattern: " + reqPattern); GregorianCalendar calendar = GregorianCalendar.from(currentUTCTime.atZone(ZoneId.systemDefault())); XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); System.out.println("But Showing As :" + xcal); I want the output as 2015-06-18 11:59:15:135, but when i set the...

JDK8 java.time.LocalTime with custom pattern

java,java-8,java-time
can anyone explain to me why this test is passed: import org.junit.Assert; import org.junit.Test; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import static org.hamcrest.core.Is.is; public class BasicTest extends Assert{ @Test public void testLocalTimeWithPredefinedPattern() throws Exception { DateTimeFormatter dtf = DateTimeFormatter.ISO_TIME; LocalTime time = LocalTime.parse("10:11:12", dtf); assertThat(time.toString(), is("10:11:12")); } /** * It's...

How to convert from org.joda.time.DateTime to java.time.ZonedDateTime

java,datetime,timezone,jodatime,java-time
I have a data source with joda time DateTime objects stored. I need to convert them into java ZonedDateTime objects, keeping the original timezone. It is not sufficient to keep the offset since some DateTime objects represents daily repetitive tasks, and these tasks must occur at a specific time in...

Converting a time to milliseconds correctly in java.time (Java 8)

java,date,java-8,java-time
I've been trying to convert a "DateTime" to milliseconds using the java.time package built into Java 8. But I haven't been able to do it correctly. I am trying to convert "29/Jan/2015:18:00:00" to milliseconds. The following is something I tried Instant instant = Instant.parse("2015-01-29T18:00:00.0z"); Long instantMilliSeconds = Long.parseLong(instant.getEpochSecond() + ""...

Get original pattern String given a JDK 8 DateTimeFormatter?

java,java-8,datetime-format,java-time,jsr310
Related to my question here - how do I get the original pattern String given a DateTimeFormatter?

Parse date miliseconds to days,hours,minutes

java,android,datetime,android-date,java-time
I'm trying to get parse a string to date, and after that to get the days,hours,minutes from the miliseconds. I'm parsing this string to date:2015-03-01 00:00:00, and that im doing with this code: DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date inputDate = dateFormat.parse(data.get(position).getValidTo()); long ms = inputDate.getTime(); Now after this...

How to get first seconds of the next day based on current seconds?

java,datetime,java-time
I have to convert seconds in UTC into day then add interval of one day and return seconds in UTC. Here is what I have: option #1 public static final long nextDayStartSec(long epochSecondsInUTC) { return (epochSecondsInUTC / TimeUnit.DAYS.toSeconds(1) + 1) * TimeUnit.DAYS.toSeconds(1); } But not all days contain 86400 seconds...

Java8 LocalDate Time Adding Hours Not Wroking

java-8,java-time
I tried like below, but in both the cases it is showing same time? What i am doing wrong. LocalDateTime currentTime = LocalDateTime.now(ZoneId.of("UTC")); Instant instant = currentTime.toInstant(ZoneOffset.UTC); Date currentDate = Date.from(instant); System.out.println("Current Date = " + currentDate); currentTime.plusHours(12); Instant instant2 = currentTime.toInstant(ZoneOffset.UTC); Date expiryDate = Date.from(instant2); System.out.println("After 12 Hours =...

Is it safe to naively replace System.currentTimeMillis() with Clock.systemDefaultZone().millis()?

java,datetime,java-time
Java 8 introduces the java.time.Clock interface, which should allow me to mock out system time calls effectively (awesome!). I'd like to naively replace calls to System.currentTimeMillis() with calls to someClock.millis(), but it isn't clear to me that these two clocks will actually return the same values in all cases based...

Where are the Java 8 DateTimeFormatters constants defined?

java,java-8,datetime-format,java-time,jsr310
I am looking at the DateTimeFormatter class and I was wondering where are the constants like "M", "EEE" and "YY" etc are defined. More specifically there should be code like this somewhere given a ChronoField and TextStyle, it should return the DateTimeFormatter string snippet e.g. (ChronoField.MONTH_OF_YEAR, TextStyle.SHORT) should map to...

Is it possible to truncate date to Month with Java 8?

java,java-8,truncate,java-time
I want to get the milliseconds truncated to days, I can use Instant.now().truncatedTo(ChronoUnit.DAYS).toEpochMilli() But I can't truncate to ChronoUnit.MONTH (it throws an exception). Do I need use a Calendar?...

java.time.Instant -> java.sql.Timestamp behaving differently on Windows vs *nix (timezone-related)

java,hibernate,timestamp,jodatime,java-time
Somewhere in the code I have Timestamp ts = Timestamp.from(instant); where instant is, as the name suggests, java.time.Instant. (Why? To allow Hibernate 4.x to persist, via a UserType, JDK8 time types, not yet supported before Hibernate 5). In fact, let me put the code so it's clear. The log statement...

Convert time based on timezone using java.time

java,time,java-8,java-time
How to change the time based on timezone in LocalDateTime, here i have built a date with Time zone as EST, now i need to find the UTC of the corresponding time. please help me how to solve this String str = "16Jun2015_153556"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss"); formatter.withZone(ZoneId.of("EST5EDT")); LocalDateTime dateTime...

Parse date from string to get miliseconds

java,android,android-calendar,android-date,java-time
I'm trying to get the miliseconds from an string that contains a date, but seems that im getting the wrong value. This is the string im trying to parse: 2015-03-01 00:00:00, I'm doing this to parse it: DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); Date inputDate = dateFormat.parse(data.get(position).getValidTo()); Log.d("--", inputDate.getDay() +...

Java 8 DateTimeFormatter parsing for optional fractional seconds of varying significance

java,java-time,datetime-parsing
My MCVE (as a TestNG unit test): public class MyDateTimeFormatterTest { private static final String BASE_PATTERN = "yyyy/MM/dd HH:mm:ss"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(BASE_PATTERN + "[.SSSSSSSSS]"); private static final LocalDateTime TEST_INPUT = LocalDateTime.of(2015, 5, 4, 12, 34, 56, 123456789); @DataProvider(name = "test-cases") public Iterator<Object[]> getTestCases() { return Arrays.asList(testFor("",...

DateTimeFormatter month pattern letter “L” fails

java,date,java-8,java-time
I noticed that java.time.format.DateTimeFormatter is not able to parse out as expected. See below: import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Play { public static void tryParse(String d,String f) { try { LocalDate.parse(d, DateTimeFormatter.ofPattern(f)); System.out.println("Pass"); } catch (Exception x) {System.out.println("Fail");} } public static void main(String[] args) { tryParse("26-may-2015","dd-L-yyyy"); tryParse("26-May-2015","dd-L-yyyy"); tryParse("26-may-2015","dd-LLL-yyyy");...

JSR-310 - parsing seconds fraction with variable length

java,java-time
Is there a way how to create JSR-310 formatter that is able to parse both following date/times with variable length of seconds fraction? 2015-05-07 13:20:22.276052 or 2015-05-07 13:20:22.276 Example code: DateTimeFormatter formatter = new java.time.format.DateTimeFormatterBuilder() .append( java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") ) .appendOptional( java.time.format.DateTimeFormatter.ofPattern(".SSSSSS") ) .toFormatter(); formatter.parse("2015-05-07 13:20:22.276052", LocalDateTime::from); ...

What is the difference between year and year-of-era?

java-8,java-time
The DateTimeFormatter class documentation defines separate symbols u for year and y year-of-era: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns What is the difference between year and year-of-era?...

Duration to TemporalUnits

java-time
How do I convert a duration to a set of temporal units? I have a duration, and I want to divide that into for instance whole years, whole days and fractional seconds. I have found PeriodFormatterBuilder for JodaTime, but it seems to facilitate printing as well as division into units,...

How do i format a java.time.Duration mm:ss

java,java-8,java-time
I have a java.time.Duration and I want to output it in the form of mm:ss. It doesnt seem possible to use DateTimeFormatter since that only accepts LocalTime, ZonedTIme ectera So I did it like this, works fine for 90 seconds give 1:30, but for 66 seconds gives 1:6 whereas I...

How to parse non-standard month names with DateTimeFormatter

java,datetime,localization,java-8,java-time
I need to parse (German) dates that come in the following form: 10. Jan. 18:14 8. Feb. 19:02 1. Mär. 19:40 4. Apr. 18:55 2. Mai 21:55 5. Juni 08:25 5. Juli 20:09 1. Aug. 13:42 [...] As you can see, the month names are cut if the month has...

Not getting correct timezone in Java 8?

java,java-8,java-time
I have set my system data time to Asia/Kolkata and it is: Date: 2015-06-12 Time: 12:07:43.548 Now i have written following program in Java 8 ZoneId paris = ZoneId.of("Europe/Paris"); LocalDateTime localtDateAndTime = LocalDateTime.now(); ZonedDateTime dateAndTimeInParis = ZonedDateTime.of(localtDateAndTime, paris ); System.out.println("Current date and time in a particular timezone : " +...

How to deal with 'optional' T in ISO-8601 timestamp in Java 8 / JSR 310 / threeten.org ?

java,datetime,java-8,java-time
In Java 8 time / JSR 310 / threeten.org backport ... Q: How do I parse ISO-8601 timestamps with either a 'T' or a space ' ' between the date portion and the time portion? ISO-8601 format for timestamps specifies the literal 'T' to separate the date specification from the...

DateTimeFormatter auto-corrects invalid (syntactically possible) calendar date

java,parsing,date,formatting,java-time
Java DateTimeFormatter throws an exception for when you try a date that goes outside of a possible range, for example: DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy"); String dateString = "12/32/2015"; LocalDate ld = LocalDate.parse(dateString, dtf); will throw: Exception in thread "main" java.time.format.DateTimeParseException: Text '12/32/2015' could not be parsed: Invalid value for DayOfMonth...