get SimpleDateFormat return wrong answer - java

I need to convert timestamp string to long.
Here is my input string:
2016-08-10T11:24:57.182+0300
here is code witch I am trying to use for converting:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.sssZ");
try {
Date date = simpleDateFormat.parse(timestamp);
long time = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
result: 1470817622000
but when i check this long time here, it returns me this string:
10 august 2016 8:27:02 GMT
but this is different from the input string.
any idea why it happens and how to fix this?

Related

How do I convert 09/24/2015 into 20150924?

How can one convert the input date formatted as mm/dd/yyyy into an integer formatted as yyyymmdd.
I tried:
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
String input = "09/25/2015";
String t;
t = ft.format(input);
and
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
String input = "09/25/2015";
String t;
try{
t = ft.parse(input);
}catch (ParseException e){
}
}
Neither of these worked; The first one gave me a runtime error.
Assuming the input date is in type of a String:
String strDate = "09/24/2015";
String[] tok = strDate.split("/");
System.out.println(tok[2] + tok[0] + tok[1]);
You can split them into tokens.
You can do it in two ways: String manipulation, or date parsing and reformatting.
// String substitution using regular expression
System.out.println("09/24/2015".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
// Lenient date reformatting
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("MM/dd/yyyy").parse("09/24/2015")));
String substitution will do nothing for bad formats, and will convert good formats even if date values are bad.
The date reformatting will fail (exception) for bad formats, and will "adjust" bad date values (see below), because it's lenient by default. Change to strict to also fail on bad date values:
// Strict date reformatting
SimpleDateFormat mdy = new SimpleDateFormat("MM/dd/yyyy");
mdy.setLenient(false);
SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
System.out.println(ymd.format(mdy.parse("09/24/2015")));
The above three methods will all print:
20150924
To show the effect of bad date values,a dn with bad formats:
// Showing results with bad date
System.out.println("09/34/2015".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("MM/dd/yyyy").parse("09/34/2015")));
try { ymd.format(mdy.parse("09/34/2015")); } catch (Exception e) { System.out.println(e); }
// Showing results with bad formats
System.out.println("Hello".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
try { new SimpleDateFormat("MM/dd/yyyy").parse("Hello"); } catch (Exception e) { System.out.println(e); }
try { ymd.format(mdy.parse("Hello")); } catch (Exception e) { System.out.println(e); }
Output
20150934
20151004
java.text.ParseException: Unparseable date: "09/34/2015"
Hello
java.text.ParseException: Unparseable date: "Hello"
java.text.ParseException: Unparseable date: "Hello"

Java Unparseable Date difference in formats

How to differentiate between data-entry being (a) invalid date or (b) invalid format?
I have the following code for handling date inputs from an text file.
public boolean dateIsValid(String date) {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
try {
Date dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
I have everything working as I want it to. The only problem I have is I am unable to differentiate the different parse exceptions thrown. For example:
if String date = 18/10/2012 --> java.text.ParseException: Unparseable date: "18/10/2012"
if String date = 2-12-2001 --> java.text.ParseException: Unparseable date: "2-12-2001"
As you can see, both the wrong formats throw the same error. How can I differentiate them so that I can handle them differently?
EDIT
To be more precise, in case of date 18/10/2012, I should throw an invalid date error and in the case of date 2-12-2001, I need to throw an invalid format exception. I dont need to handle different formats. I just need a way of getting different exceptions for these two different cases.
The issue seems to be at this line
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
For the first error it looks like that the date is coming first and the month later so it should be like
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Second error shows the incorrect format of the date supplied since it is containing - whereas you are expecting the format containing / ie like
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
If you want to handle different formats then try like this:
String[] formatDates= {"MM/DD/yyyy", "dd/MM/yyyy", "MM-dd-yyyy","dd-MM-yyyy"};
Date tryParse(String dateString)
{
for (String formatDate: formatDates)
{
try
{
return new SimpleDateFormat(formatDate).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Unless you write code to parse the date strings yourself, you will not know why the format threw the exception.
I recommend a variation of the R. T. answer above.
Specifically, instead of creating a new formatter every time, create four (in that example) formatters at startup (in the constructor or in a static block).
I would use
public Date dateIfValid(String format, String date) {
DateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
try {
return dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
return null;
}
}
Date mmddyy = dateIfavlid("MM/dd/yy", date.replace("[^0-9]", "/"));
Date ddmmyy = dateIfavlid("dd/MM/yy", date.replace("[^0-9]", "/"));
if (mmddyy != null && ddmmyy == null) {
Note: this can be used to detect ambigous dates such as 01/02/03 which might be 3rd Feb 2001

how to convert zeroes to date

i get the single value from String array.this single value have zeroes.i want convert this zeroes to date and gettime...
String followupdate2="";
for(int i=1;i<2;i++){
followupdate2=followupdate1[i];
System.out.println("--------------"+followupdate2);
}
System.out.println("---------outer-----"+followupdate2);
SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yy");
Date followupdate3=format1.parse(followupdate2);
long followupdate4=followupdate3.getTime();
followupdate2 have 00-000-00
i want convert followupdate2 to date ....
i want get long followupdate4=followupdate3.getTime();
error is:
java.text.ParseException: Unparseable date: "00-000-00"
at java.text.DateFormat.parse(Unknown Source)
You are feeding your program bad input. The output is TELLING YOU that you are feeding it bad input.
Use a try-catch block and deal with it.
SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yy");
long followupdate4;
try {
Date followupdate3=format1.parse(followupdate2);
followupdate4 = followupdate3.getTime();
} catch (ParseException e) {
followupdate4 = 0; //Whatever you want here.
}

Parsing time string and changing timezone

I am retrieving data from a webservice that provides a timestamp in the form of HH:mm:ss I am using SimpleDateFormat to convert this string into a date object then change its timezone if needed and also convert it from 24hour to 12 hour time.
Problem: When a time is fed in for 12am it looks like this 00:00:00
so 12:05 is 00:05:00
When i get the results they look like this.
times fed in 22:00:00 to 00:01:00
times retrieved 10:00 pm to 0:01 am
I have been looking around to see if there is a way to fix it but i feel like i will need to make a special case and parse the string myself if it has a 0 in the hours place.
Any help would be greatly appreciated.
public String parseTime(String time) {
String mTime = null;
TimeZone thisTimeZone = TimeZone.getDefault();
TimeZone ourTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
SimpleDateFormat sdfThisTimeZone = new SimpleDateFormat("K:mm:a",
Locale.getDefault());
Date date = null;
sdfThisTimeZone.setTimeZone(thisTimeZone);
sdf.setTimeZone(ourTimeZone);
try {
date = sdf.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mTime = sdfThisTimeZone.format(date.getTime());
//**********************************New: Does Not Work********************************
DecimalFormat nft = new DecimalFormat("00"); mTime = nft.format(mTime);
//**********************************New **********************************************
return mTime;
}
I have tried the line using DecimalFormat but i just copied it into the code for now to see if it would work. Unfortunately it made my app crash. The code that i have posted is executed inside an Async Task so i am not sure if that makes any difference but still thankyou for your help. Eventually i will solve this. But for now it is such a small detail that only occurs for 1 hour at 12am that i am moving on to bigger issues. If anyone can shed some light on this that would be awesome.
String getConvertedDateTime (String dateTime) {
String convertedDateTime = dateTime;
if (convertedDateTime != null
&& !convertedDateTime.equalsIgnoreCase("")
&& !convertedDateTime.equalsIgnoreCase("null")) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Calendar calendar = Calendar.getInstance();
java.util.Date convertedDate = formatter
.parse(convertedDateTime);
formatter.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
convertedDateTime = formatter.format(convertedDate.getTime());
} catch (Exception e) {
e.printStackTrace();
}
}
return convertedDateTime;
}

Java convert date to readable form?

I have Date objects stored in database. Now am when the form I am displaying presents all the data in my objects, it also displays date. I don't want it to show the long detailed form. All I need is DD/MM/YYYY format. This is what am getting now:
Sun Jan 01 00:00:00 GMT+03:00 2012
Now I followed an online tutorial and got this code going:
public String changeDateFormat(Date date){
String pattern = "MM/dd/yyyy";
//Date datex = null;
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
date = format.parse(date.toString());
System.out.println(date);
} catch (ParseException e) {
System.err.print(e);
}
return date.toString();
}
and I invoke it when am getting the value of global variable:
public String getEndDate() {
return changeDateFormat(endDate);
}
the output shown above is the result. What can I do to only and only get DD/MM/YYYY without time if possible?
Thanks
Just
return (new SimpleDateFormat("dd/MM/yyyy").format(dateInstance));

Categories