Converting timestamp from parse.com in java - java

I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.
public static String timeAgo(String time){
PrettyTime mPtime = new PrettyTime();
long timeAgo = timeStringtoMilis(time);
return mPtime.format( new Date( timeAgo ) );
}
public static long timeStringtoMilis(String time) {
long milis = 0;
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sd.parse(time);
milis = date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return milis;
}
The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?

Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds.
Change it to:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
to fix it.
Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.

Expanding #Tom's answer:
The problem
When hardcoding 'Z', you assume that all dates were saved as UTC - which doesn't necessarily have to be the case.
The problem is that SimpleDateFormat does not recognize the literal 'Z'as an alias for UTC's '-0000' offset (For whatever reason, since it claims to be ISO-8601 compliant).
So you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
since this wrongly assumes all dates will always be written as in UTC, but you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
either, since this would not be able to parse the date when the literal 'Z' occurs.
Solution 1: Use javax.xml.bind.DatatypeConverter
This datatype converter actually is ISO8601 compliant and can be used as easy as
import javax.xml.bind.DatatypeConverter;
public Long isoToMillis(String dateString){
Calendar calendar = DatatypeConverter.parseDateTime(dateString);
return calendar.getTime().getTime();
}
If you use JAXB anyway, that would be the way to go.
Solution 2: Use conditional formats
final static String ZULUFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final static String OFFSETFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/* This is a utility method, so you want the calling method
* to be informed that something is wrong with the input format
*/
public static Long isoToMillis(String dateString) throws ParseException{
/* It is the default, so we should use it by default */
String formatString = ZULUFORMAT;
if(! dateString.endsWith("Z") ) {
formatString = OFFSETFORMAT;
}
SimpleDateFormat sd = new SimpleDateFormat(formatString);
return sd.parse(dateString).getTime();
}
If you don't already use JAXB, you might want to put this method into a utility class.

Related

String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]

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.

Android method for consistent DateTime formatting across application

My application queries a SQLite DateTime string and I'm trying to write a single method than I can use across my application so that DateTime timestamps are formatted consistently. So far I have,
public class DateTimeUtils {
public static String formatDueDate(String queryResponse) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss z", Locale.US);
Date result = new Date();
try {
result = sdf.parse(queryResponse);
} catch (ParseException e) {
e.printStackTrace();
}
return result.toString();
}
}
Which is used in a situations such as
taskViewHolder.mDue.setText(formatDueDate(task.getDue().toString()));
I'd like the output to look like June 27, 20015, 5:30PM
The raw datetime String takes the form: 2015-08-10T17:28:00.000-04:00
My problems are currently the resulting timestamp format is incorrect and instead looks like Sun Aug 02 17:29:03 EDT 2015 and instead of parsing the inputted timestamp, just returns the current datetime.
I believe this is because my formatting is actually throwing an exception and i'm just returning the current Date() object. What should I change so that the datetime string is parsed correctly?
Well, since you're creating the Date object outside the try block, you're right, if there is a parsing error, the current date will return. SimpleDateFormat does that work for you in the parse method. You could reduce the possibility of the current date returning by assigning the Date variable to null instead of instantiating a new object.
If you already get an correct Date class, maybe you can generator your special format by Calendar class and StringBuilder class.
Like below:
String[] monthString = new String[12];
if (monthString[0] == null) {
// Get month string by android locale
// The String will like Jule or May ...
Map<String, Integer> months = Calendar.getInstance().getDisplayNames(Calendar.MONTH, Calendar.LONG, getResources().getConfiguration().locale);
for (int i = 0; i < 12; i++) {
for (String month : months.keySet()) {
if (i == months.get(month).intValue()) {
monthString[i] = month;
months.remove(month);
break;
}
}
}
}
Calendar calendar=Calendar.getInstance();
calendar.setTime(result);
StringBuilder sb=new StringBuilder();
sb.append(monthString[calendar.get(Calendar.MONTH)]);
//spec your format string...
Hope this can help you.

joda time parse method return format

I have very simple question - I read couple of threads here but I still do not understand how to get simple thing. I want to send string to method and get back joda date. I had no problem to build it up, but return format is 2015-03-11T17:13:09:000+01:00. How can I get desired (e.g. mmm-dd hh:mm) format back from below mentioned method (it mustto be a dateTime for sorting purposes on FX form)? I tried to gamble with another dateTimeFormatter but had no luck. Thank you very much in advance
public static DateTime stringToDateTime(String textDate) throws ParseException
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
DateTime jodaTime = dateTimeFormatter.parseDateTime(textDate);
return jodaTime;
}
What do you mean by "return format"? "Format" term here could only be related to a string representation of a DateTime object. That means you should specify format of your input string (what you've already done in your code) - and a corresponding DateTime object will be created. After that you probably use toString() to check the results, but DateTime.toString() uses ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ) according to JavaDoc - that gives you your 2015-03-11T17:13:09:000+01:00 result.
So to get it as desired you could try using toString(String pattern) method with format you need. But once again - it's just an output format to convert DateTime to String, it doesn't affect the datetime stored in your DateTime object.
I just use Calendar object so this is a possible way to do it:
static String stringToDateTime(String textDate) {
Calendar c = new GregorianCalendar();
// How you want the input to be formatted
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = df.parse(textDate);
c.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
// How do you want to print your date
df= new SimpleDateFormat("dd-MM-yy");
return df.format(c.getTime());
}
// input
String myDate = "2015-04-15 14:25:25";
System.out.println(stringToDateTime(myDate));

How to converted timestamp string to a date in java

I have a string "1427241600000" and I want it converted to "yyyy-MM-dd" format.
I have tried, but I am not able to parse it, please review the below code
try {
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date =sf.parse(str);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
I would like to know where I went wrong.
You should try it the other way around. First get the Date out of the milliTime and then format it.
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(Long.parseLong(str));
System.out.println(sf.format(date));
the conversion is highly dependent on what format the timestamp is in. But i assume the whole thing should actually be a long and is simply the systemtime from when the timestamp was created. So this should work:
String str = ...;
Date date = new Date(Long.parseLong(str));
Use Date date =new Date(Long.parseLong(str)); to convert your String to Date object.
if you are using SimpleDateFormat() the format specified as a parameter to this function should match the format of the date in the String (str in your case). In your case yyyy-MM-dd does not match the format of the time stamp (1427241600000).
You can do it like this:
use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

How to parse date string using Timezone in GWT

Has anybody succeeded parsing date string with a custom timezone in GWT? GWT's DateTimeFormat allows to format dates based on time zone, but I haven't found any method for doing opposite operation. So what should I do if I have following string "02:01:2011" (format "MM:dd:yyyy"). It can have different results in different timezones.
The other problem appears when trying to change dates, months and etc. How can I do it based on a custom timezone?
Maybe there is any library which can simplify all these operations?
I have made workaround and add timezone part to each date string which miss that part. Still looking for a more professional solution.
Either give the timezone to the client from the server (e.g., include it in the date string) or standardize the timezone on the server so that the client can assume a constant timezone. If you include the timezone with the date string, the below code snippet should work.
I havent tested this, but according to the docs, it should work:
String dateStr = "04/21/2011 01:37:36 -0800;
DateTimeFormat format = new DateTimeFormat("MM/dd/yyyy HH:mm:ss Z");
Date date = format.parse(dateStr);
Depending on how you are representing the timezone, you can change the final variable in the format string (the Z). See the docs for details: http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html
I did the following to parse a date in the TimeZone tz.
It's probably dodgy, but it works: -
final long MILLIS_IN_MINUTE = 60000;
Date localDate = DateTimeFormat.getFormat("dd MMM yyyy HH:mm:ss").parse(dateString);
int localOffset = localDate.getTimezoneOffset() * MILLIS_IN_MINUTE;
int targetOffset = tz.getOffset(localDate) * MILLIS_IN_MINUTE;
// Subtract the offset to make this into a UTC date.
return new Date(localDate.getTime() - localOffset + targetOffset);
It parses the date in the client timezone and then adjusts it to the required timezone.
Recently I passed upon this project: gwt-calendar-class which emulates Calendar and TimeZone in javascript.
public static Date getDateGWT(final String strDate, final int style) {
Date date = null;
int useStyle = style;
if (!validStyle(style)) {
useStyle = DEFAULT_DATE_STYLE;
}
if ((strDate != null) && (strDate.trim().length() > 0)) {
DateTimeFormat df = getDateFormatGWT(useStyle);
try {
date = df.parse(strDate);
} catch (Exception e) {
date = df.parse(date.toString());
}
}
return date;
}
private static DateTimeFormat getDateTimeFormatGWT(final int style) {
switch(style) {
case SHORT:
return DateTimeFormat.getShortDateTimeFormat();
case MEDIUM:
return DateTimeFormat.getMediumDateTimeFormat();
case LONG:
return DateTimeFormat.getLongDateTimeFormat();
case FULL:
return DateTimeFormat.getFullDateTimeFormat();
default :
return DateTimeFormat.getMediumDateTimeFormat();
}
}
Try This

Categories