I want to create a Date object without a TimeZone (eg : 2007-06-21
). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);
Use this Code:
Hope it'll help you.
Date
isn't a date. It's a timestamp. That's some impressive API design, isn't it?The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.
This is the
toString()
of thejava.util.Date
So, if you will pass a Date and try to print it this will be printed out all the time.
If you want to format a date, you need to use
DateFormat
or something similar. ADate
is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. ThetoString()
method always uses the system local time zone, and always formats it in a default way. From the documentation:So it's behaving exactly as documented.
You've already got a
DateFormat
with the right format, so you just need to callformat
on it:Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like
PreparedStatement.setDate
to pass it to the database.As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (
java.time.*
) you'll have a much smoother time of it with anything date/time-related. TheDate
/Calendar
API is truly dreadful.Code:
Date :
Fri Apr 29 04:53:16 GMT 2016
Sample Output :
2016-04-29
Imports required :