Json Date to Java Date and back to Json Date - java

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)/";

Related

Convert String "01-09-2015' to Long - Java/Android

Hi I have a String like this "01-09-2015"
I need to convert this string to long.
I have tried using
String date = "01-09-2015";
Long dateLong = Long.getLong(date);
Long dateLong = Long.valueOf(date);
Long dateLong = Long.valueOf(date,36);
Long dateLong = Long.parseLong(date);
Still no help. Everything returns be NumberFormatException.
Anyone please help.
Thanks in advance.
EDIT
Guys, I will send in a String, which is of course a date like "08-01-2015". For each unique string which I pass, I need a unique long value. Thats all.
You have to convert it to Date first before changing it to Long
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date d = format.parse("01-09-2015");
long milliseconds = d.getTime();
I recommend you split the input on -, then convert the three date parts to int; and then concatenate them into a long. Something like,
String date = "01-09-2015";
String[] arr = date.split("-");
int yyyy = Integer.valueOf(arr[2]);
int mm = Integer.valueOf(arr[0]);
int dd = Integer.valueOf(arr[1]);
long dateLong = (yyyy * 10000) + (mm * 100) + dd;
System.out.println(dateLong);
Output is (the unique, per date)
20150109
Note This is in keeping with ISO 8601; the linked Wikipedia article says (in part)
ISO 8601 Data elements and interchange formats – Information interchange – Representation of dates and times is an international standard covering the exchange of date and time-related data.

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.

converting JodaTime to Long Integer format

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

Jackson deserialize Joda DateTime from Unix format

When deserializing from JSON I have dates that are written in Unix Epoch time (/Date(1379542610387+1000)/).
I understand that is it pretty standard to serialize dates in Json this way, however how can I get this value deserialized into a Joda DateTime?
When jackson see's a value like this it spits out:
Invalid format: "/Date(1379542610387+1000)/"
private static final Pattern pat = Pattern.compile("/Date\\((\d+)[\\+\\-](\\d+)\\)/");
...
String data = "/Date(1379542610387+1000)/";
Matcher m = pat.matcher(data);
if (m.matches())
{
long time = Long.valueOf(m.group(1));
int offset = Integer.valueOf(m.group(2));
System.out.printf("time=%d offset=%d\n",time,offset);
}
else
// not a date in the recognized format ...

convert a string of time to 24 hour format

I have a string holding a start time and an end time in this format 8:30AM - 9:30PM I want to be able to strip out the AM - and the PM and convert all the times to 24 hour format so 9:30PM would really be 21:30 and also have both the times stored in 2 different variables, I know how to strip the string into substrings but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM.
String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM"
String startTime;
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"
String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
Now that I think about it, SimpleDateFormat, H h K k can be confusing.
Cheers.
You need to use: SimpleDateFormat
And can refer this tutorial: Formatting hour using SimpleDateFormat
Example:
//create Date object
Date date = new Date();
//formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
String strDateFormat = "h";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println("hour in h format : " + sdf.format(date));
I wouldn't reinvent the wheel (unless you are doing this as a school project or some such).
Just get a date object out of your time stamp and then you can generate whatever format you want with this: SimpleDateFormat
[edited to address your specific request]
if you absolutely need to work from your own unique strings, then you'll do something like this (I don't know exactly what your strings look like... you're using offsets like 85, which means nothing out of context).
I didn't check this for bugs, but this is approximately what you want...
myStr = timestampString.toLowerCase(); //something like 8:30am
boolean add12 = (myStr.indexOf("pm") != -1)?true:false;
//convert hour to int
int hour = Integer.parseInt(myStr.split(":")[0]);
int minutes = Integer.parseInt( myStr.split(":")[1].replaceAll("\\D+","").replaceAll("^0+","") ); //get the letters out of the minute part and get a number out of that, also, strip out leading zeros
int militaryTime = hour + (add12)? 12:0;
if(!add12 && militaryTime == 12)
militaryTime = 0; //account for 12am
//dont' forget to add the leading zeros back in as you assemble your string
With Joda Time, the code looks like:
DateTimeFormatter formatter12 = DateTimeFormat.forPattern("K:mma");
DateTime begin = formatter12.parseDateTime(beginTime);
DateTime end = formatter12.parseDateTime(endTime);
DateTimeFormatter formatter24 = DateTimeFormat.forPattern("k:mma");
String begin24 = formatter24.print(begin);
String end24 = formatter24.print(end);
I should like to contribute the modern answer
DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
String time = "8:30AM - 9:30PM";
String[] times = time.split(" - ");
LocalTime start = LocalTime.parse(times[0], twelveHourFormatter);
System.out.println(start.toString());
LocalTime end = LocalTime.parse(times[1], twelveHourFormatter);
System.out.println(end.toString());
This prints:
08:30
21:30
I am using java.time, the modern Java date and time API. The SimpleDateFormat class used in many of the other answers is long outdated and was always troublesome. java.time is so much nicer to work with than the date-time classes from the 1990’s. A LocalTime is a time of day without a date (and without time zone), so suits your need much better than an old-fashioned Date.
Link: Oracle tutorial: Date Time explaining how to use java.time.
24 hour time adds 12 to any time greater than 12pm so that 1pm is 13 and so on until 24 or 12am. Here is the sudo code:
if(hour <= 12)
{
hour = hour + 12;
}
All the below lines will works when
String str="07:05:45PM";
and when you call timeConversion(str) and want to convert to 24 hours format..
public class TimeConversion {
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");
static String timeConversion(String s) {
String str = null;
try {
str= TWENTY_FOUR_TF.format(
TWELVE_TF.parse(s));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws ParseException {
String str="07:05:45PM";
System.out.println(timeConversion(str));
}
}

Categories