Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Java8 Date Time API


When working with date and time objects in Java 8 you will probably need to work with date periods and time durations. A date period is measured in days, months, and years, while a time duration is measured in hours, minutes, and seconds. A duration can be computed using the Duration class, and a period can be computed using the Period class. Both classes are located in the java.time package.


Example of Date Time API



DateTimeApi.java

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class DateTimeApi {

public static void main(String[] args) {

LocalDate july4th2017 = LocalDate.of(2017, Month.JULY, 4);
LocalDate august10th2018 = LocalDate.of(2018, Month.AUGUST, 10);
DateTimeFormatter format=DateTimeFormatter.ofPattern("MM/dd/yy");
Period period=Period.between(july4th2017, august10th2018);

System.out.format("Period between %s and %s is %d year,
%d month, %d days \n" ,
july4th2017.format(format), august10th2018.format(format),
period.getYears(), period.getMonths(), period.getDays());

//Current timestamp
Instant timestamp = Instant.now();
System.out.println("Current Timestamp = "+timestamp);

//Instant from timestamp
Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
System.out.println("Specific Time = "+specificTime);

//Duration example
Duration thirtyDay = Duration.ofDays(30);
System.out.println(thirtyDay.toDays());

LocalDateTime dateOfBirthAndTime = LocalDateTime.of(LocalDate.of(1985,
Month.SEPTEMBER, 20), LocalTime.of(22, 10));
LocalDateTime deathDateAndTime = LocalDateTime.now();
long duration = Duration.between(dateOfBirthAndTime,
deathDateAndTime).toDays();

System.out.println("Number of days alive = " + duration);
}
}



     << Previous
Next >>