converting JodaTime to Long Integer format - java

hello I had date format which i use in a API call in Long integer format. That API call does not support date in any other format and it should as follows.
public static long start_date=20140401101010L;
public static long end_date=20140430101010L;
I had to make some changes in that date, so i changed that date into JodaDate format as like the below code.
DateTime startDateTime = formatter.parseDateTime(String.valueOf(start_date));
DateTime endDateTime = formatter.parseDateTime(String.valueOf(end_date));
This is how we convert normal variable to DateTime object. so how can i do the opposite.? If i have a JodaTime 2014-04-30T10:10:10.000+05:30 and i want to change that time to this format which is as a Long integer. 20140430101010L . I want to do this because i am doing an API program and the url parameter has time and which support only the above format and not in JodaTime.

Format your joda time object as a string, and then convert to a long.
You would need a formatter that outputs in the format you want
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
String formatted = formatter.format(datetime);
long lvalue = Long.parseLong(formatted).longValue();

One solution would be to use a DateTimeFormat to build the String then parse it as a Long.

If you really need a long in that format, which i would seriously question:
long dateTimeLong = year * 10000000000L
+ month * 100000000L
+ date * 1000000L
+ hours * 10000L
+ minutes * 100L
+ seconds * 1L;
You say you need an URL parameter though, which is a string, and not a long. So just use
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
String dateTimeString = formatter.print(dateTime);

public class DateConverter {
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
private final DateTime dateTime;
public DateConverter(DateTime dateTime) {
this.dateTime = dateTime;
}
private Long toLong() {
return Long.valueOf(dateTime.toString(formatter));
}
public static void main(String [] args) {
System.out.println(new DateConverter(DateTime.now()).toLong());
}
}
And the output:
20140623131922
Process finished with exit code 0

Related

How to convert timestamp date to java.util date(yyyy-mm-dd) in java

I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.
Any help on this would be really appreciated
You can easily convert a java.sql.Timestamp to a java.time.LocalDate and get a date String by formatting the LocalDate like this:
public static void main(String[] args) {
// just a timestamp stub that takes "now"
java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
// convert it to a modern date object
LocalDate justDate = ts.toLocalDateTime().toLocalDate();
// print it using a suitable formatter
System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output (today) is
2020-02-17
You just need Java 8 or higher for this or import a backport library.
EDIT
If you don't need a String but a java.util.Date, do it with Instant only, like this:
public static void main(String[] args) {
// just a timestamp stub that takes "now"
Instant now = Instant.now();
Timestamp ts = Timestamp.from(now);
// create an Instant from the Timestamp
Instant timestampInstant = ts.toInstant();
// and then create a Date out from that Instant
java.util.Date creationDate = java.util.Date.from(now);
// do something with the Date here...
}
But please consider using java.time wherever possible, which might be in your domain class...
private String getZonedDateTime(String startTime){
// input -> startTime: 2020-02-17T09:40:37.850+0000
// output -> 2020-02-17
return ZonedDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
Just pass the Date String which you have and get it in what format you want.
That question is answered here
And what you want exactly, to display the date with that format or save with that format.
If you want display the date with (yyyy-mm-dd)
String dateFormated = new SimpleDateFormat("yyyy-MM-dd").format(myTimestamp);
System.out.println(dateFormated);
If you want save the date with that format you can try to do this:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd);
String dateFormated = dateFormat.format(myTimestamp);
Date parsedDate = dateFormat.parse(dateFormated);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) {
}

Converting timestamp from parse.com in 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.

String to joda LocalDate in format of "dd-MMM-yy"

I am using JAXB and joda time 2.2. to backup the data from Mysql to XML and restore it back. in my Table I have a Date attribute in format of "16-Mar-05". I successfully store this in XML. but when I want to read it from XML and put it back in Mysql table, I cant get the right format.
this is my XMLAdapter class, here in unmarshal method the input String is "16-Mar-05", but I cant get the localDate variable in the format of "16-Mar-05", although I am setting pattern to "dd-MMM-yy". I posted all the options I tried, how can I get my localDate in "dd-MMM-yy" like 16-Mar-05format?
Thanks!!
public class DateAdapter extends XmlAdapter<String, LocalDate> {
// the desired format
private String pattern = "dd-MMM-yy";
#Override
public String marshal(LocalDate date) throws Exception {
//return new SimpleDateFormat(pattern).format(date);
return date.toString("dd-MMM-yy");
}
#Override
public LocalDate unmarshal(String date) throws Exception {
if (date == null) {
return null;
} else {
//first way
final DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
final LocalDate localDate2 = dtf.parseLocalDate(date);
//second way
LocalDate localDate3 = LocalDate.parse(date,DateTimeFormat.forPattern("dd-MMM-yy"));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
return localDate4;
}
}
So I took your code and ran it and it works fine for me...
The problem, I think, you're having is that you're expecting a LocalDate object to maintain the format that you original parsed the object with, this is not how LocalDate works.
LocalDate is a representation of date or period in time, it is not a format.
LocalDate has a toString method which can be used to dump the value of the object, it, this is a internal format used by the object to provide a human readable representation.
To format the date, you need to use some kind of formater, that will take the pattern you want and a date value and return a String
For example, the following code...
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String date = "16-Mar-05";
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
LocalDate localDate2 = dtf.parseLocalDate(date);
System.out.println(localDate2 + "/" + dtf.print(localDate2));
//second way
LocalDate localDate3 = LocalDate.parse(date, DateTimeFormat.forPattern("dd-MMM-yy"));
System.out.println(localDate3 + "/" + dtf.print(localDate3));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
System.out.println(localDate4 + "/" + FORMATTER.print(localDate4));
Produced...
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
Before you get upset about this, this is how Java Date works as well.

Json Date to Java Date and back to Json Date

I looked through all possible answer here but I am having hard time to figure this thing out.
I have Json date in a String. I want to convert into a Java Date without losing time.
Also I would like to convert from Java Date to Json Date string.
Here what I have.
String jsonDateString = "/Date(1295157600000-0600)/";
There are 2 parts in your time : the local time in milliseconds, and the offset in hours and minutes. You have to parse them and "add" them to get the milliseconds UTC.
You may do it using this function :
private static Pattern p = Pattern.compile("\\((\\d+)([+-]\\d{2})(\\d{2})\\)");
public static Date jd2d(String jsonDateString) {
Matcher m = p.matcher(jsonDateString);
if (m.find()) {
long millis = Long.parseLong(m.group(1));
long offsetHours = Long.parseLong(m.group(2));
long offsetMinutes = Long.parseLong(m.group(3));
if (offsetHours<0) offsetMinutes *= -1;
return new Date(
millis
+ offsetHours*60l*60l*1000l
+ offsetMinutes*60l*1000l
);
}
return null;
}
To make "back" a JSON date, I would simply encode the UTC time :
String jsonDate = "/Date("+date.getTime()+"+0000)/";

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