I ma getting exeception while parsing the date.
following is the code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date d = format.parse("2014/02/20");
System.out.println(d);
Not only have you got the slashes/dashes wrong, you're also using DD (day of year) instead of dd (day of month). You want:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
As always, read the documentation to find out exactly what pattern symbols mean - and if you find it's behaving oddly, check the pattern against the data very carefully.
I would also recommend:
Using Joda Time (pre-Java-8) or java.time (Java 8) if you possibly can; the java.util.Date/Calendar API is horrible
Specifying the locale explicitly
Specifying the time zone explicitly
Currently you're using the default time zone and locale. While the locale may not matter in this case (unless it's used to pick the calendar system; I can't remember offhand) I think it's clearer to explicitly specify it. The time zone definitely matters; if you only ever want to treat this as a date (no time) it's probably worth specifying UTC - that way it's easy to interoperate with anything else, and you get day boundaries in obvious places in the underlying millisecond representation.
Your dateformat doesn't match your string.
Date d = format.parse("2014-02-20");
or
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Related
If I take current date from my application, it comes with variation like below:
scenario 1: when the date is less than 10th of the month, a month is less than 10 of the year --> example: 5/9/18
scenario 2: when the date is >= 10th of the month, a month is less >= 10 of the year --> example: 10/11/18
Note: all the examples are in MM/DD/YY format and timezone is the USA
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy HH:mm a");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
The above piece of code throwing me an error when the scenario 1 is in place. But if I format the date-time as "M/d/yy H:mm a" it works for both the scenario. I need the date add also.
Will it be a good practice to use the 2nd format? or there is any other way to get it done. Expert guidance please..
java.time
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.US);
ZonedDateTime dayBeforeYesterday = ZonedDateTime.now(ZoneId.of("America/St_Thomas"))
.minusDays(2);
System.out.println(dayBeforeYesterday.format(formatter));
Running just now I got this output:
5/7/18, 8:44 AM
Please specify your desired time zone where I put America/St_Thomas. Think twice before you use ZoneId.systemDefault() for your JVM’s time zone setting since this setting may be changed at any time from other parts of your program or other programs running in the same JVM; but if you trust the setting reflects the user’s time zone, it’s the correct thing to use.
Rather than defining your own output format prefer using one of the built-in formats you get from DateTimeFormatter.ofLocalizedDateTime. Do specify locale (no matter if you use a built-in format or roll your own). Again, use Locale.getDefault() if you trust the JVM’s setting is correct.
Avoid the old date and time classes like Calendar, DateFormat and SimpleDateFormat. They are not only long outdated, they are also poorly designed and the last two in particular notoriously troublesome. Today we have so much better in java.time, the modern Java date and time API.
Link: Oracle tutorial: Date Time explaining how to use java.time.
The number of characters in the format MM indicates that two digits are required in the input. A single character M will match one or two digits. Use M/d/yy H:mm a to support your desired formats.
I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();
I have a varaibles:
Date date;
Time time;
and methods:
MyDateMethod(Date date){
//do stuff
}
MyTimeMethod(Time time){
//do stuff
}
I tried using MyDateMethod() with the following call:
MyDateMethod(1995-03-7);
I get an error saying I've supplied it with type int when it expected type Time.
I also tried using MyTimeMethod() with the following call:
MyTimeMethod(03:04:55);
I get an error saying Type mismatch: Cannot convert type int to boolean.
What is the format to put in a variable of these different types? Date is obviously not xxxx-xx-xx and Time is obviously not xx:xx:xx.
There are a few options,
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse("1995-03-07");
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
Output is
Tue Mar 07 00:00:00 EST 1995
Or, you could use
// -1 because January is 0... I didn't design it!
Calendar c = new GregorianCalendar(1995, 3 - 1, 7);
System.out.println(c.getTime());
with the same output as before.
SimpleDateFormat is what You need. It's need to be initialized by format of date.
Use it like this:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss", Locale.getDefault());
and then:
Date date = (Date) dateFormat.parse("2014/04/02 22:22:22");
Take a look at DateFormat and particularly SimpleDateFormat.
Your example would be coded like this, using SimpleDateFormat:
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1995-03-07")
(I'm assuming you have months before days here, you will need to interchange the MM and dd if not).
Java does not support Date literals. You need to use a constructor or a static factory method to obtain an instance of this class.
1995-03-07 returns 1985 because you have three int literals here and the hyphens are interpreted as subtraction operators.
Take a look at the documentation for the Date class and the DateFormat class
Here's a way you could represent these values:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("1995-03-07");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date time = timeFormat.parse("03:46:16");
You can use the same format objects to perform the reverse of this conversion. Please mind that these Date instances represent a specific moment in time, down to millisecond level. Internally, this is represented as the number of milliseconds since January 1, 1970, 00:00:00 GMT
This API is hardly the prettiest one in Java and by looking at the docs you can see how many changes it has undergone. Just look at the number of deprecated methods.
I recommend taking a look at the Joda-Time library instead.
Alternatively, if using Java 8 is an option for you, you can try the brand new API that comes with it
The answer by Tom is correct. No date-time literals inJava.
And as he stated, the old bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either the Joda-Time library or the new java.time package in Java 8.
Joda-Time
In Joda-Time:
If you want only a date without time and time zone, use the LocalDate class.
Similarly to use only time while ignoring time zone and date, use the LocalTime class.
But most often you'll probably want to use the DateTime class which tracks date, time, and time zone all in one object.
A Date-Time Is Not Text
A DateTime object does not contain text. No String. If you need a string representation, use a formatter object to generate one. Search StackOverflow for many examples.
Built into Joda-Time are formatters for the sensible and increasingly common ISO 8601 standard. For example, the toString implementation on the DateTime class produces a String like this…
2014-04-01T20:17:35-08:00
I call a service which returns GMT dates. Its been working fine since November, but now with daylight savings time active, its failing. Here's a sample date from non-daylight savings time:
2011-12-07T15:50:01Z
And one from today (in daylight savings time):
2012-03-26T11:05:01+01:00
Previously I've been using this pattern:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
But its failing on the second date above with a ParseExcepton ("Unparsable date..."). So, can one pattern be used for both, and if so what is it? If I can't use one pattern for both, what is the correct pattern for the second date above?
It shouldn't make a difference, but if it does this is in use on the Android platform.
It definitely makes a difference that you're using Android, as it would make a difference in this case if you were using Java 5/6 or 7.
The pattern you're using specifies a literal 'Z' (also 'T') to be parsed. It is not parsing a timezone. You need to drop the single-quotes from around the 'Z' to start parsing an actual time-zone.
According to the Android JavaDoc, it is unclear whether a capital Z will even work in this case, as the format of the hours/minutes is pretty specific. I don't know enough about the Android SDK to confirm, but the colon definitly makes a difference in standard Java.
The new ISO8601 time zone pattern is covered by the X pattern specifier which is introduced in Java 7.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.UK);
If you're still on Java 6 or older, then yes it may make difference. You'll need either to parse it (partially) yourself or to grab Joda Time.
In case you use java6, you will have to identify the patterns and then apply the formater
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String date2Str="2011-12-07T15:50:01Z";
Date date2 = df.parse(date2Str);
System.out.println(date2.toString());
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
String date1Str="2012-03-26T11:05:01GMT+01:00";
Date date1 = df2.parse(date1Str);
System.out.println(date1.toString());
I have a string obtained by calling the toString method of an instance of the class Date. How can I get a Date object from this string?
Date d = new Date();
String s = d.toString;
Date theSameDate = ...
UPDATE
I've tried to use SimpleDateFormat, but I get java.text.ParseException: Unparseable date
What is the date format produced by Date.toString ()?
If your real goal is to serialize a Date object for some kind of custom made persistence or data transfer, a simple solution would be:
Date d = new Date();
long l = d.getTime();
Date theSameDate = new Date(l);
You could do it like this
Date d = new Date();
String s = d.toString;
Date theSameDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(s);
If your real goal is to serialize and deserialize a date and time (for data transfer or for persistence, for example), serialize to ISO 8601, the standard format for date and time data.
Skip the long outdated Date class. The modern Java date and time API known as java.time is so much nicer to work with. The class you need from it is probably Instant (this depends on your more exact requirements).
The two points go nicely hand in hand:
Instant i = Instant.now();
String s = i.toString();
Instant theSameInstant = Instant.parse(s);
The modern classes’ toString methods produce ISO 8601 format (e.g., 2018-01-11T10:59:45.036Z), and their parse methods read the same format back. So this snippet is all you need, and you get an instant equal to the first, with nanosecond precision.
If you cannot control the string you get, and you get the result from Date.toString(), the format pattern string in Sedalb’s answer works with java.time too:
DateTimeFormatter dtf
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
Date d = new Date();
String s = d.toString();
Instant nearlyTheSameInstant = ZonedDateTime.parse(s, dtf).toInstant();
It’s essential to provide a locale. Otherwise the JVM’s default locale will be used, and if it’s not English, parsing will fail. In the worst case you will see your code running fine for many years and suddenly it will break when one day someone runs it on a computer or device with a different locale setting.
The point from jambjo’s answer still applies: The three and four letter time zone abbreviations used in Date.toString() are very often ambiguous, so there is no guarantee that the time zone is interpreted correctly, and again, it will be interpreted differently on different JVMs.
Finally, Date.toString() does not render the milliseconds that the Date holds, which leads to an inaccuracy of up to 999 milliseconds. If using the string from Date.toString(), there is nothing we can do about it (which was why I named the variable nearlyTheSameInstant).
Take a look at SimpleDateFormat#parse(). It should provide the functionality you're looking for.
Date theSameDate = new Date(Date.parse(s));
For some not so obvious reasons, this is not a particularly good idea. You can find details on that in the API documentation for the parse method. One problem is e.g. that the time zone abbreviations are ambiguous, so that the parser may fail in interpreting the correct time zone.