java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) throws ParseException {
LocalDate date = LocalDate.parse("2016-04-28");
System.out.println(date);
// In case you also need time-part as 00:00
LocalDateTime ldt = date.atTime(LocalTime.MIN);
System.out.println(ldt);
}
}
Output:
2016-04-28
2016-04-28T00:00
The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter
object explicitly as long as the Date-Time string conforms to the ISO 8601 standards. Your date string is already in the ISO 8601 format.
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time
API with JDBC.
What went wrong with your code?
By default SimpleDateFormat
uses the default timezone while parsing any string. Given below is the code to reproduce your error:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.parse("2016-04-28").toInstant());
}
}
Output:
2016-04-27T18:30:00Z
In order to keep the time part 00:00:00
, you need to set UTC timezone to the SimpleDateFormat
instance.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.parse("2016-04-28").toInstant());
}
}
Output:
2016-04-28T00:00:00Z
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.