This question already has answers here:
SimpleDateFormat parsing date with 'Z' literal [duplicate]
(12 answers)
Closed 4 years ago.
I am using the below code to format millisecond resolution date strings. It works for 2018-09-14T13:05:21.329Z but not 2018-09-14T13:05:21.3Z. Can anybody suggest the reason and how to correct it?
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date parsedDate = formatter.parse(date);
String destDate = sdfDestination.format(parsedDate);
return destDate;
} catch (java.text.ParseException parseException) {
logger.error("Parse Exception occured while converting publication time to date "
+ "format 'yyyy-MM-dd HH:mm:ss'", parseException);
}
I get below exception:
java.text.ParseException: Unparseable date: "2018-09-14T13:05:21.3Z"
at java.text.DateFormat.parse(Unknown Source) ~[na:1.8.0_181]
at com.noordpool.api.implementation.utility.Utility.parseDate(Utility.java:136) [classes/:na]
at com.noordpool.api.implementation.utility.Utility.parseMessage(Utility.java:77) [classes/:na]
Your only problem is that you are using a wrong pattern for SimpleDateFormat, you need to change:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
To:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Because the Z used in the date string means "zero hour offset" so you just need to pass it as 'Z' in your pattern.
This is a working demo with the right pattern.
Edit:
And to make things work with different Locales and Timezones, you need to use the appropriate Locale when you are creating the SimpleDateFormat instance, this is how should be the code:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
The only possible issue I can see is that you're passing in milliseconds incorrectly and the program doesn't know what to do about it.
So the last part of the formatter indicates with milliseconds and a timezone as .SSSX
But how does it evaluate 3Z for the input into this? I mean, do you say it's 300 timezone Z, or say it's 003 timezone Z, or worse, try and parse it as 3Z, which hopefully you see that you cannot turn '3Z' into a number.
To remedy this, I'd validate your input 'date' and ensure the milliseconds part is always 3 digits long, this removes the ambiguity and the program always knows that you mean '300 milliseconds, timezone Z'.
There is a problem in java 8 where the number of characters that you specified with the formatter should be an exact match (which is not specified in the documentation).
You can use three different Formatters and use nested exception as follows:
DateFormat format1 = new SimpleDateFormat("y-M-d'T'H:m:s.SX");
DateFormat format2 = new SimpleDateFormat("y-M-d'T'H:m:s.SSX");
DateFormat format3 = new SimpleDateFormat("y-M-d'T'H:m:s.SSSX");
Date parsedDate;
try {
// Parsing for the case - 2018-09-14T13:05:21.3Z
parsedDate = format1.parse(date);
} catch (ParseException e1) {
try {
// Parsing for the case - 2018-09-14T13:05:21.32Z
parsedDate = format2.parse(date);
} catch (ParseException e2) {
try {
// Parsing for the case - 2018-09-14T13:05:21.329Z
parsedDate = format3.parse(date);
} catch (ParseException e2) {
//The input date format is wrong
logger.error("Wrong format for date - " + date);
}
}
}
java.time
DateTimeFormatter dtfDestination
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String date = "2018-09-14T13:05:21.3Z";
String destDate = Instant.parse(date)
.atZone(ZoneId.of("Indian/Comoro"))
.format(dtfDestination);
System.out.println(destDate);
Output from this snippet is:
2018-09-14 16:05:21
Please substitute your correct time zone if it didn’t happen to be Indian/Comoro, since correct output depends on using the correct time zone. If you want to use your JVM’s default time zone, specify ZoneId.systemDefault(), but be aware that the default can be changed at any time from other parts of your program or other programs running in the same JVM.
I am exploiting the fact that your string, "2018-09-14T13:05:21.3Z", is in ISO 8601 format, the format that the classes of java.time parse as their default, that is, without any explicit formatter. Instant.parse accepts anything from 0 through 9 decimals on the seconds, so there is no problem giving it a string with just 1 decimal, as you did. In comparison there is no way that an old-fashioned SimpleDateFormat can parse 1 decimal on the seconds with full precision since it takes pattern letter (uppercase) S to mean milliseconds, so .3 will be parsed as 3 milliseconds, not 3 tenths of a second, as it means.
Jahnavi Paliwal has already correctly diagnosed and explained the reason for the exception you got.
The date-time classes that you used, DateFormat, SimpleDateFormat and Date, are all long outdated and SimpleDateFormat in particular is notoriously troublesome. Since you seem to be using Java 8 (and even if you didn’t), I suggest you avoid those classes completely and use java.time instead.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Related
This question already has answers here:
Java Date Error
(8 answers)
Closed 4 years ago.
I want to convert String values in the format of mm/dd/yy to YYYY-MM-DD Date. how to do this conversion?
The input parameter is: 03/01/18
Code to convert String to Date is given below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When tried to convert using this method it shows the following error
java.text.ParseException: Unparseable date: "03/01/18"
As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.
To Convert as Date,
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);
To Print it out in the other format,
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)
You are writing it the wrong way. In fact, for the date you want to convert, you need to write
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
The format you are passing to SimpleDateFormat is ("yyyy-MM-dd") which expects date to be in form 2013-03-01 and hence the error.
You need to supply the correct format that you are passing your input as something like below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
The solution for the above problem
Convert the String date value in the Format of "dd/mm/yy" to Date.
By using the converted Date can able to frame the required date format.
The method has given below
public static String stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
String dateString = null;
try {
// convert to Date Format From "dd/mm/yy" to Date
date = formatter.parse(dateVlaue);
// from the Converted date to the required format eg : "yyyy-MM-dd"
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.
public static Optional<LocalDate> stringToDateLinen(String dateValue) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
try {
return Optional.of(LocalDate.parse(dateValue, dateFormatter));
} catch (DateTimeParseException dtpe) {
return Optional.empty();
}
}
Try it:
stringToDateLinen("03/01/18")
.ifPresentOrElse(System.out::println,
() -> System.out.println("Could not parse"));
Output:
2018-01-03
I recommend you stay away from SimpleDateFormat. It is long outdated and notoriously troublesome too. And Date is just as outdated. Instead use LocalDate and DateTimeFormatter from java.time, the modern Java date and time API. It is so much nicer to work with. A LocalDate is a date without time of day, so this suites your requirements much more nicely than a Date, which despite its name is a point in time. LocalDate.toString() produces exactly the format you said you desired (though the LocalDate doesn’t have a format in it).
My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.
What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null is a NullPointerException waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError if the situation is not supposed to happen. In my code I am returning an Optional, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException. In the code calling the method I am using the ifPresentOrElse method introduced in Java 9. If not using Java 9 yet, use ifPresent and/or read more about using Optional elsewhere.
What went wrong in your code?
The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.
Link
Oracle tutorial: Date Time explaining how to use java.time.
This question already has answers here:
Date and time conversion to some other Timezone in java
(11 answers)
Closed 8 years ago.
I have a string with gmt date value and -06:00 at end. What is best way to convert this to CST? I looked at other questions but none of them have -06:00 at end to answer my question.
This is what I tried and it errors out as java.text.ParseException: Unparseable date: "2015-02-19T11:50:09.5953377-06:00"
private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSSSSS'Z'");
private DateFormat gmtFormat = new SimpleDateFormat();
private TimeZone cstTime = TimeZone.getTimeZone("CST");
gmtFormat.setTimeZone(cstTime);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
System.out.println("cst start date is " + gmtFormat.format("2015-02-19T11:50:09.5953377-06:00"));
} catch (ParseException e) {
e.printStackTrace();
}
I've run into similar problems before, where I was actually getting dates in 3 different iso formats like that, and was pretty frustrated with it... This isn't pretty, but it may help point you in the right direction...
The 3 formats I was getting the info in:
private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String ISO_FORMAT2 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static final String ISO_FORMAT3 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
Actually attempting to parse them (without having to figure out the correct type beforehand, returning a new Date Object in the event all 3 failed so shit doesn't crash because of a damn date formatting exception):
public static Date parseIso(String date){
SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e) {
Log.g(TAG, "Failed 1st date parse with " + ISO_FORMAT + " for " + date);
sdf = new SimpleDateFormat(ISO_FORMAT2, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e2) {
Log.g(TAG, "Failed 2nd date parse with " + ISO_FORMAT2 + " for " + date);
sdf = new SimpleDateFormat(ISO_FORMAT3, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e3) {
Log.g(TAG, "Failed 3rd date parse with " + ISO_FORMAT3 + " for " + date);
}
}
}
return new Date();
}
And then for actually converting that date to a localized date:
public static String format(long mils, String format){
return format(getInstance(mils), format);
}
public static String format(Calendar calendar, String format){
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(new Date(calendar.getTime().getTime() + TimeZone.getDefault().getOffset(new Date().getTime())));
}
public static Calendar getInstance(long timeInMils){
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(timeInMils);
return cal;
}
So now you can basically call
CalendarHelper.format(myDateObject.getTime(), "MMM dd, yyyy");
and it will return the localized, formatted date from the original UTC date you received.
Again, not pretty, but I hope this can point you in the right direction for converting between the UTC and client's time zone. Best of luck~
PS. I think ISO_FORMAT_3 is the one that will actually help you. I guess I probably could have started with that information, but I'm not a bright man.
ISO 8601
You seem to misunderstand the meaning of the input string, 2015-02-19T11:50:09.5953377-06:00. You do not have a "gmt date value".
That format appears to be the standard ISO 8601 format.
The T in the middle separates the date portion from the time-of-day portion.
The -06:00 at the end is an offset from UTC. It means "the date-time value shown here is six hours behind UTC".
CST
So, if by CST you mean Central Time Zone (some of the middle parts of the Americas continents), then you need have no conversion to perform. That string with the time 11:50 means "almost noon in Illinois, Arkansas, and Louisiana". If you add 6 hours to 11:50, you would learn the UTC (GMT) date-time at that same moment: 17:50 on same date.
Avoid 3-4 Letter Codes
By the way, avoid using three or four letter time zone codes such as "CST". Those codes are not standardized nor unique. Many duplicates exist. For example, take CST:
Central Standard Time (Americas)
China Standard Time
Central Standard Time (Australia)
Central Summer Time (Australia)
Cuba Standard Time
Instead use proper time zones. Most of these are continent plus a slash plus a city/region. Examples: America/Regina, America/Monterrey, and America/Indiana/Knox.
Joda-Time | java.time
The java.util.Date/.Calendar classes are notoriously troublesome. Avoid them.
Use either the Joda-Time library or the new java.time package built into Java 8. The java.time package is inspired by Joda-Time but is re-architected. Each has its own strengths and weaknesses.
Both Joda-Time and java.time use ISO 8601 formats as their defaults for both parsing and generating string representations of date-time values.
As this Question is really a duplicate with hundreds of such Questions and Answers already posted, I'll give just one quick example.
String input = "2015-02-19T11:50:09.5953377-06:00";
DateTimeZone zoneAmerica_Regina = DateTimeZone.forID( "America/Regina" );
DateTime dateTimeAmericaRegina = new DateTime( input, zoneAmerica_Regina );
DateTime dateTimeLosAngeles = dateTimeAmericaRegina.withZone( DateTimeZone.forID( "America/Los_Angeles" ) );
DateTime dateTimeUtc = dateTimeAmericaRegina.withZone( DateTimeZone.UTC );
Fractional Seconds
Your input string has a very small fraction of a second. Joda-Time (like java.util.Date) handles only millisecond resolution — three digits after the decimal point. The java.item package handles nanosecond resolution. Some systems use microsecond resolution, such as database like Postgres. And some systems follow the old Unix convention of whole seconds.
I need to change the SimpleDateFormat to some other format which is equivalent in jodatime.
Here's the code which needs to be changed.
public static String dateFormat(Date date, String format)
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
I have tried to use DateTimeFormatter.
public static String dateFormat(DateTime date, String format)
{
DateTimeFormatter dtf = DateTimeFormat.forPattern(format);
DateTime tempDateTime = dtf.parseDateTime(date.toString());
return tempDateTime.toString();
}
But I am getting Error.
Well, I look for you in the documentation of Joda Time and SimpleDateFormat. As you can see there, the pattern definitions are unfortunately not the same. If you translate from SimpleDateFormat to Joda-DateTimeFormat, then you have to note following items:
Change Y to x (so called week-year).
Change y to Y (year-of-era) and maybe changing the chronology, too (from ISO to Gregorian/Julian)
W is not supported in Joda Time (week of month), hence no replacement!
F is not supported in Joda Time (day of week in month), hence no replacement!
Change u to e (day number of week - ISO order, not localized), available since Java 7.
The symbol S is handled differently (I suppose in Joda Time better because of correct zero padding).
The zone symbol z is in Joda Time not allowed for parsing (maybe this is the current cause of your problems - you have not shown your pattern format or your exception yet).
The zone/offset symbol Z is handled better in Joda Time, for example allows colons in offset etc. If you need latter you can use X in SimpleDateFormat which has the replacement Z in Joda Time.
Some tests added:
Following sample code demonstrates the different handling of format symbol S.
String s = "2014-01-15T14:23:50.026";
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS");
DateTime instant = dtf.parseDateTime(s);
System.out.println(dtf.print(instant)); // 2014-01-15T14:23:50.0260
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS");
Date date = sdf.parse(s);
System.out.println(sdf.format(date)); // 2014-01-15T14:23:50.0026 (bad!)
Another test for format symbol z (is that your problem???):
String s = "2014-01-15T14:23:50.026PST";
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
DateTime instant = dtf.parseDateTime(s);
System.out.println(dtf.print(instant)); // abort
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2014-01-15T14:23:50.026PST" is malformed at "PST"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)
at time.JodaTest8.main(JodaTest8.java:83)
SimpleDateFormat can do this zone name parsing (although at least dangerous sometimes):
String s = "2014-01-15T14:23:50.026PST";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
Date date = sdf.parse(s);
System.out.println(sdf.format(date)); // 2014-01-15T14:23:50.026PST
// Im new to java programming
I have a String object that represents a date/time in this format : "2013-06-09 14:20:00" (yyyy-MM-dd HH:mm:ss)
I want to convert it to a Date object so i can perform calculations on it but im confused on how to do this.
I tried :
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(date);
//Prints Mon Dec 31 00:00:00 GMT 2012
Any help appreciated
Ok so I have now updated my code to as follows i'm getting the correct date/time now when I print the date but is this the correct implementation :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(dateFormat.format(date));
//prints 2013-06-09 14:20:00
Thx to everyone that's answered/commented thus far
The format is wrong. Use this instead:
"yyyy-dd-MM HH:mm:ss"
Indeed your last program version is ok, except you don't need to declare the SimpleDateFormat twice. Simply:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = dateFormat.parse(string);
System.out.println(dateFormat.format(date));
String string = "2013-06-09 14:20:00";
and the DATE object format is "yyyy-dd-MM HH:mm:ss"
You can get Date,Day,month and many more by using Date object which is present in
java.util.Date package , like as follows.
Date d = new Date(string);
This will call constructor of Date object for which you are passing 'string' variable which contains date.
d.getDay(); // retrieve day on that particular day
d.getDate(); // retrieve Date
and many more are avaiable like this.
Using java.util.Date
The answer by zzKozak is correct. Well, almost correct. The example code omits required exception handling. Like this…
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = null;
try {
date = dateFormat.parse(string);
} catch ( ParseException e ) {
e.printStackTrace();
}
System.out.println("date: " + dateFormat.format(date));
Don't Use java.util.Date!
Avoid using java.util.Date & Calendar classes bundled with Java. They are notoriously bad in both design and implementation.
Instead use a competent date-time library. In Java that means either:
The third-party open-source Joda-Time
In the forthcoming Java 8, the new java.time.* classes defined by JSR 310 and inspired by Joda-Time.
Time Zone
Your question and code fail to address the issue of time zones. If you ignore time zones, you'll get defaults. That may cause unexpected behaviors when deployed in production. Better practice is to always specify a time zone.
Formatter
If you replace a space with a 'T' per the standard ISO 8601 format, then you can conveniently feed that string directly to a constructor of a Joda-Time DateTime instance.
If you must use that string as-is, then define a formatter to specify that format. You can find many examples of that here on StackOverflow.com.
Example Code
Here is some example code using Joda-Time 2.3, running in Java 7.
I arbitrarily chose a time zone of Montréal.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( "2013-06-09T14:20:00", timeZone ); // Or pass DateTimeZone.UTC as time zone for UTC/GMT.
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2013-06-09T14:20:00.000-04:00
I've been struggling for a while with this piece of code for an Android app and I can't get the hang of it. I've read and tried every solution I found on stackoverflow and other places, but still no luck.
What I want to do is have a function to convert a string like "17.08.2012 05:35:19:7600000" to a UTC date and a function that takes an UTC date and converts it to a string like that.
String value = "17.08.2012 05:35:19:7600000";
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
try
{
Date today = df.parse(value);
System.out.println("Today = " + df.format(today) + " " + today.toGMTString());
}
catch (ParseException e)
{
e.printStackTrace();
}
This results in : Today = 17.08.2012 07:41:59:0000000 17 Aug 2012 04:41:59 GMT which are both wrong.
I tried setting SDF's timezone to UTC, no luck.
Another thing that I noticed: if I do df.setLenient(false);
It gives me : java.text.ParseException: Unparseable date: "17.08.2012 05:35:19:7600000" .
If anyone can provide me with some explanations / sample code, I would be very grateful. Thanks in advance
The result you are getting is absolutely right.
Let's analyze this:
17.08.2012 05:35:19:7600000
17: Day of month (17th)
08: Month of year (August)
2012: Year (2012)
05: Hour of day (5am)
35: Minute of hour (:35)
19: Second of minute (:19)
7600000: Milliseconds of second (7,600,000)
Now, the way the VM sees this is that you are declaring the time of day as 5:35:19am, then adding 7,600,000 milliseconds to it. 7,600,000 milliseconds = 7,600 seconds = 2 hours, 6 minutes, 40 seconds. 5:35:19am + 02:06:40 = 7:41:59am (and 0 milliseconds). This is the result you are getting. (It also appears that you are not setting the timezone properly, so the GMT string is 3 hours behind your result.)
If you want to retain the :7600000, to my knowledge this is not possible. As this can be simplified into seconds, the VM will automatically reduce it into the other time increments. The milliseconds (the SSSS) should be for storing values <1000.
I'd suggest you create a new SimpleDateFormat for your output; but remember that the milliseconds will be absorbed into the other times (since they are all stored as a single long in the Date object).
private String convertDate(String cdate)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
Date convertedDate;
try
{
convertedDate = dateFormat.parse(cdate);
cdate = postFormater.format(convertedDate);
}
catch (ParseException e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
}
return cdate;
}
Try this.
This is what you need (but it will loose millisecond information):
"dd.MM.yyyy HH:mm:ss.'000000'"
If you used "dd.MM.yyyy HH:mm:ss.SSSSSS", then would get three leading zeros for your milliseconds.
If you used "dd.MM.yyyy HH:mm:ss.SSS'000'", then you could format a date, but not parse any date.
Try it out:
public static void main(String[] args) throws ParseException {
printDate("dd.MM.yyyy HH:mm:ss.SSS");//02.05.2010 21:45:58.073
printDate("dd.MM.yyyy HH:mm:ss.SSSSSS");//02.05.2010 21:45:58.000073
printDate("dd.MM.yyyy HH:mm:ss.SSS'000'");//02.05.2010 21:45:58.073000
printDate("dd.MM.yyyy HH:mm:ss.'000000'");//02.05.2010 21:45:58.000000
tryToParseDate("dd.MM.yyyy HH:mm:ss.SSS");//good
tryToParseDate("dd.MM.yyyy HH:mm:ss.SSSSSS");//good
tryToParseDate("dd.MM.yyyy HH:mm:ss.SSS'000'");//bad
tryToParseDate("dd.MM.yyyy HH:mm:ss.'000000'");//good
}
private static void printDate(String formatString) {
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat(formatString);
String formattedDate = format.format(now);
// print that date
System.out.println(formattedDate);
}
private static void tryToParseDate(String formatString) {
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat(formatString);
String formattedDate = format.format(now);
// try to parse it again
try {
format.parse(formattedDate);
System.out.println("good");
} catch (ParseException e) {
System.out.println("bad");
}
}
To drop the nanoseconds, use:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.")
Update: java.time
The Question and other Answers use terrible date-time classes that are now legacy. These flawed classes were years ago supplanted by the modern java.time classes defined in JSR 310. Avoid Calendar, DateFormat, Date, etc.
Define a formatting pattern with DateTimeFormatter.
String input = "17.08.2012 05:35:19:7600000";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm:ss:SSSSSSS" );
Parse.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
A LocalDateTime object represents a date with a time of day, but lacks the context of a time zone or offset from UTC.
If you are certain the input text is intended to represent a moment as seen in UTC, having an offset of zero hours-minutes-seconds, then assign a ZoneOffset to produce an OffsetDateTime object.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
See this code run live at Ideone.com.
ISO 8601
I suggest you educate the publisher of your data about the use of ISO 8601 standard formats when serializing date-time values to text.
The java.time classes use ISO 8601 formats by default when parsing/generating text.