Im having a problem with java date's, when i pass a date before 1949 into the bellow method.
The date i have returned is for example 2049, im aware it has somthing to do with the date format and thought using yyyy instead of RRRR would have fixed it. But i just dont understand why or how to reslove it. Any help will be much apreciated
public static java.sql.Date parseDate(String date) throws ParseException {
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return null;
}
Thanks Jon
let me format that for you..
public static java.sql.Date parseDate(String date) throws ParseException {
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return null;
}
This I suspect is what you want...
private Date convertDate() throws ParseException
{
String dateStr = "21-02-2010";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
if (dateStr != null)
{
date = new Date(dateFormat.parse(dateStr).getTime());
}
System.out.println(date);
return date;
}
For 21-02-2010 you will get...
Sun Feb 21 00:00:00 GMT 2010
For 21-02-1938 you will get...
Mon Feb 21 00:00:00 GMT 1938
Does that help? I might of been due to you having MMM in your code.
tl;dr
java.sql.Date.valueOf(
LocalDate.parse( "12-Jan-23" , DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) )
)
Time Zone
Your code ignores the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone.
Your code uses Date which is always in UTC. So your date value produced from the misnamed Date class will be accurate for UTC but not valid for other time zones such as America/Montreal or Asia/Kolkata.
Using java.time
The modern way to do this work is with the java.time classes that supplant the troublesome old legacy date-time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
To parse an incoming string, define a formatting pattern with DateTimeFormatter. Specify a Locale for the human language to be used in translating the name of the month.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US );
LocalDate localDate = LocalDate.parse( "12-Jan-2017" , f );
With JDBC 4.2 and later, you can pass the LocalDate directly to your database with setObject and getObject methods.
For a JDBC driver not yet updated, fall back to the java.sql types.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
LocalDate localDate = sqlDate.toLocalDate();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
This question already has answers here:
Calendar returns date in wrong time zone
(5 answers)
Getting the current time millis from device and converting it into a new date with different timezone [duplicate]
(2 answers)
DateFormat parse - not return date in UTC
(1 answer)
Closed 4 years ago.
We are converting database date into required user timezone. But if we format using jodatime in string format we are getting correct date and if we parse string to get date object we are getting wrong time. Here is my code. I tried jodatime parser and java date
public class Test {
public static void main(String[] args) {
String dateF = "01/19/2019 at 07:35 PM (UTC)";
String dateFormat = "MM/dd/yyyy 'at' hh:mm a (zzz)";
long time = 1603305000;
String timeZone = "Etc/UTC";
Locale locale=new Locale("en", "US");
DateTimeFormatter dateFormatter = null;
if (locale.equals(Locale.FRENCH)) {
dateFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale);
} else {
dateFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(null);
}
if (true) {
dateFormatter = dateFormatter.withZone(DateTimeZone.forID(timeZone));
}
// Old Logic using Java Time
DateFormat format3 = new SimpleDateFormat(dateFormat, locale);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
if(true)
format3.setTimeZone(TimeZone.getTimeZone(timeZone));
DateTime jodatime = new DateTime(time);
try {
System.out.println(dateFormatter.print(jodatime));
System.out.println("timezone converted Date : " + format3.parse(dateFormatter.print(jodatime)));
System.out.println("dateFormatter.parseDateTime converted Date : " + dateFormatter.parseDateTime(dateFormatter.print(jodatime)).toDate());
} catch (Exception e) {
System.out.println(e);
}
}
}
Correct date in Formatted string 01/19/1970 at 01:21 PM (UTC)
We are getting a wrong result after parsing
timezone converted Date : Mon Jan 19 18:51:00 IST 1970
dateFormatter.parseDateTime converted Date : Mon Jan 19 18:51:00 IST 1970
Correct date in Formatted Date : Mon Jan 19 01:21:00 UTC 1970
Avoid legacy date-time classes
You are using terrible old classes bundled with the earliest versions of Java. These have been supplanted entirely by the modern java.time classes.
You are also apparently mixing those legacy classes with classes from the Joda-Time library. Firstly, that mixing is ill-advised. Secondly, Joda-Time is now in maintenance-mode, with its creators advising migration to java.time. Actually, both Joda-Time and java.time projects are led by the same man, Stephen Colebourne, with the first project having been the inspiration and education for the second.
Smart objects, not dumb strings
We are converting database date
Then avoid all the string manipulations you are doing.
As of JDBC 4.2, you can directly exchange java.time objects with your database. For a moment, meaning a column of a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE, use OffsetDateTime class.
myPreparedStatement.setObject( … , myOffsetDateTime ) ;
…and…
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Most databases store moments in UTC. You may want to adjust into a time zone for presentation to users. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Generate text in a certain format by using DateTimeFormatter object. Either specify a custom formatting pattern or automatically localize by calling ofLocalized… methods.
All of this has been covered many many many times on Stack Overflow already. Search to learn more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I need to format a string date with given time zone and return the date object back. I am currently in IST time zone.
So IST is 5 hours and 30 minutes ahead of UTC.
public void getDate(){
String dateStr = "11/25/2016T13:30:00.000";
String dateFormat = "MM/dd/yyyy'T'HH:mm:ss.SSS";
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(date);
}
public static Date formatedStringToDate(final String date, final String dateFormat) throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsedDate = null;
if (date != null) {
try {
parsedDate = sdf.parse(date);
} catch (ParseException e) {
throw e;
}
}
return parsedDate;
}
I get the below out put.
Fri Nov 25 19:00:00 **IST** 2016
The time seems to be change from 5.30 hours but then if its a IST to UCT time converstion, it should be 5.30 hours before 13:30:00 which is 08:00:00?
Also how could I change the highlighted IST part of out put string to show the currect time zone in this case UTC?
When you call toString on a Date (by printing it) you get the default format (because a Date is an object that stores a number of milliseconds, or nanoseconds in Java 9+, since an epoch). To see the result in UTC you need something like,
final DateFormat sdf = DateFormat.getDateTimeInstance(DateFormat.FULL,
DateFormat.FULL);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(sdf.format(date)); // <-- format the Date
tl;dr
LocalDateTime.parse( "2017-11-25T13:30:00.000" )
.atZone( ZoneId.of( "Asia/Kolkata" ) )
2017-11-25T13:30+05:30[Asia/Kolkata]
java.time
The modern approach uses the java.time classes that replaced the troublesome old legacy date-time classes.
Parse your input string as a LocalDateTime given the lack of any indicator of zone or offset-from-UTC.
Using standard ISO 8601 format for such strings is preferred. The java.time classes use the standard formats by default when parsing/generating strings.
LocalDateTime ldt = LocalDateTime.parse( "2017-11-25T13:30:00.000" ) ;
ldt.toString(): 2017-11-25T13:30
If you are certain this date-time was intended to represent a moment by the wall-clock time of India, then assign a time zone to produce a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2017-11-25T13:30+05:30[Asia/Kolkata]
You can adjust into another zone for comparison.
ZonedDateTime zdtMontreal = zdt.withZoneSameInstant( ZoneId.of( "America/Montreal") );
zdtMontreal.toString(): 2017-11-25T03:00-05:00[America/Montreal]
To parse/generate strings in other formats such as the one in your Question, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Search Stack Overflow for more info, as these have been covered extensively.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu'T'HH:mm:ss.SSS" , Locale.US ) ;
Use that formatter for parsing.
LocalDateTime ldt = LocalDateTime.parse( "11/25/2016T13:30:00.000" , f ) ;
And for generating.
String output = ldt.format( f ) ; // Generate string.
Consider using ISO 8601 formats instead.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am trying to convert a date string in format "yyyyMMddHHmmss" to a date string for another Time Zone "America/Sao_Paulo" taking DST into consideration for America/Sao_Paulo ( which start on 16-oct-2016 ).
I am using TimeZone class as
TimeZone represents a time zone offset, and also figures out daylight
savings.
import java.util.TimeZone;
import java.text.*;
import java.util.Date;;
public class TimeZoneConversion {
public static void main(String[] args)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
try
{
String inputdate = "20161016052355";
Date t = sdf.parse(inputdate);
System.out.println(t);
}
catch(ParseException e)
{
}
}
}
Output for the above is shown in IST
Sun Oct 16 12:53:55 IST 2016
How can i convert the the time string with input "yyyyMMddHHmmss" to a time string in "America/Sao_Paulo" Time Zone with DST in output ?
You are simply printing it in a timezone where it is not daylight savings time on that date - printing a Date prints it in the JVM's default timezone.
For instance, replacing System.out.println(t) with:
SimpleDateFormat out = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss zzzz");
out.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(out.format(t));
prints:
2016/10/16 05:23:55 Brasilia Summer Time
Ideone demo
java.time
You are using troublesome old date-time classes, now supplanted by the java.time classes.
Your input lacks any offset-from-UTC or time zone info. So we parse as a LocalDateTime, meaning any locality.
String input = "20161016052355";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f );
ldt.toString(): 2016-10-16T05:23:55
A LocalDateTime is not a moment, not a point on the timeline. To give it real meaning, you must provide the intended time zone (or offset).
ZoneId z = ZoneId.of( "America/Sao_Paulo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2016-10-16T05:23:55-02:00[America/Sao_Paulo]
To see the same moment as UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
instant.toString(): 2016-10-16T07:23:55Z
See this code run live at IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Please check with this...
please replace your specific time_zone
string dts = "May 16, 2010 7:20:12 AM CDT";
DateTime dt =
DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "yyyyMMddHHmmss", null);
This worked for me
try
{
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddhhmmss");
f.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
Date time = f.parse("20161015113634");
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
formatter.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(formatter.format(time));
}
catch (ParseException e){
}
Input : 20161015113634 (Time which is not in DST)
Output: 20161015030634 (Converted time for SaoPaulo)
Input : 20161016113634 (Time in DST)
Output: 20161016040634 (Converted time for SaoPaulo with DST Offset)
I have a POST end-point that takes a couple of values, one being endDate and startDate. When the JSON posts in as:
{ "startDate" : "2015-01-30", "endDate" : "2015-12-30" }
Spring converts it to a java.util.Date Object that is always one day behind. In the logs I see:
Validating that startDate Thu Jan 29 16:00:00 PST 2015 < endDate Tue Dec 29 16:00:00 PST 2015
So it got the timezone correct. I had assumed it was related to UTC conversions, but I'm not sure how to configure this or modify it so that it converts it using the proper off-set. The timestamp portion of it isn't required - I only care that the year, day, and month match what is passed in.
if it matters, I'm using Spring (happened with 4.0.6 and 4.1.7) and a POST
tl;dr
LocalDate.parse( "2015-01-30" )
Use the right data type for the job
You are trying to fit a date-only value into a date-time type, java.util.Date. Square peg, round hole. While trying to come up with a time-of-day to associate with your date, a time zone is being injected, hence your problem.
LocalDate
Solution:
Never use the terrible old legacy date-time classes such as java.util.Date. Use only the modern java.time classes.
For a date-only value, use LocalDate.
Your input string happens to be in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2015-01-30" ) ;
ZonedDateTime
If you want a moment, a date with a time-of-day, let java.time determine the first moment of the day. Never assume that moment is 00:00:00. In some zones on some dates it may be another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
ZonedId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of that date in that zone.
Instant
To adjust from to UTC (same moment, different wall-clock time), extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust to UTC. Same moment, same simultaneous point on the timeline, different wall-clock time.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
String str="2015-01-30";
try{
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
isoFormat.setTimeZone(TimeZone.getTimeZone("PST"));
Date date = isoFormat.parse(str);
System.out.println(date);
}catch(ParseException e){
e.printStackTrace();
}
Check here http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-webdatabinder how to customize automatic Spring conversion:
#Controller
public class MyFormController {
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
// ...
}
How do I convert the current date into string in Java?
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
Use a DateFormat implementation; e.g. SimpleDateFormat.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
tl;dr
LocalDate.now()
.toString()
2017-01-23
Better to specify the desired/expected time zone explicitly.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
java.time
The modern way as of Java 8 and later is with the java.time framework.
Specify the time zone, as the date varies around the world at any given moment.
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ; // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;
2017-01-23
By default you get a String in standard ISO 8601 format.
For other formats use the java.time.format.DateTimeFormatter class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Faster :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
Most of the answers are/were valid.
The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
You will get a deprecated message for similar calls.
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
The new way of doing this is using the Calendar Instance.
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised.
For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
This is more synonymous to real life
We get a Calendar object and we look for the time in it.
( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic
altogether)
Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters
One more way to do this is using Joda time API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
For time as YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
import org.joda.time.DateTime;
public static Date getDateByString(String dateTime) {
if(dateTime==null || dateTime.isEmpty()) {
return null;
}
else{
String modified = dateTime + ".000+0000";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj = new Date();
Date dateObj1 = new Date();
try {
if (dateTime != null) {
dateObj = formatter.parse(modified);
}
} catch (ParseException e) {
e.printStackTrace();
}
return dateObj;
}
}