Parse JSON in UNIX date in Java/Android without any library - java

I have a JSON array received from my server. I obtain a date as a timestamp String – for example, [{"date": "1418056895", ... }] – and I need to parse it in our day format. How do I do this? I have tried but I always have the year as 1970.
Note: My JSON format is in UNIX.
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setTimeStamp(feedObj.getString("date"));
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getTimeStamp() {
return timeStamp;
}
In another class, I parse the timestamp to display it:
List<FeedItem> feedItems = ...;
FeedItem item = feedItems.get(position);
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
However the displayed date is always in 1970.
Using values such as 1403375851930 it appears to work as expected (it displays a contemporary date).

If you are parsing JSON correctly,
feedObj.getString("date");
holds your date. You are reading date as String. You have to convert it to long.
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
Long timestamp = Long.parseLong("1418056895"); //Long.parseLong(feedObj.getString("date"));
cal.setTimeInMillis(timestamp * 1000L);
DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); // what ever format you need.
System.out.println(format.format(cal.getTime())); // this will be in MM/dd/yyyy
//item.setTimeStamp(format.format(cal.getTime()));
}
you can also use feedObj.getLong("date"); to get Date in long format directly, but it depends on which JSON library you using.

I don't really understand what you are trying to ask here. But if you're asking is to ow to convert that date that you get in human readable form then you should take a look at Epoch Converter. The date is returned to you in epoch timestamp. You can convert the same to a human readable form n java by using the following code.
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));

I have checked your api documentation and the date you have in response is in unix time format as described here wall.post
You can convert it using the method described here Convert Unix time stamp to date in java
Once converted you can format the date as described below.
private List<FeedItem> feedItems;
TextView timestamp
FeedItem item = feedItems.get(position);
Long timeObject = Long.parseLong(getTimeStamp());
//use the timeObject and convert it in the String as described
// in above link to convert timestamp in date object than in String
//Once available set it again in timestamp
timestamp.setText(formattedDate);

Related

Can we convert any string date value to Date yyyy-MM-dd in java?

I have a column called start_date in database and the field has a mapping in model class like
#Column(name = "start_date")
#Temporal(TemporalType.TIMESTAMP)
Date startDate
and in my pojo the same field I have as
String startDate;
from UI I am getting the string value and I want to convert that string to date and store into database
modelObj.setStartDate(parse(pojoObj.getStartDate())
and here is the parse() method
private Date parse(String dateValue){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(dateValue);
return date;
}
this code is working fine when I am providing date in yyyy-MM-dd format but not working in dd-MM-yyyy or yyyy-MMM-dd or MMM dd, yyyy any other format.
can I someone help me how can I persist the date field irrespective it's format.
As String I am able to store but I want to store it as date.
I give you a solution, the database uses BIGINT (20),and Pojo use "Long".
When saving to the database, use a timestamp of length 13, Only need to convert to timestamp when receiving the parameter, and convert the timestamp to any format when returning data.
You could iterate over all your date formats and try to parse the input to a date.
If you can parse exactly one input to a date then you are fine.
If you cannot parse the input, then you need to add a date format to your list.
If you can parse the input to more than one date and the dates are not the same, then you need to think how to proceed :-D
The code could look like
private Date parse(String dateValue) {
final List<SimpleDateFormat> simpleDateFormats = Arrays.asList(
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("dd.MM.yyyy"));
final List<Date> dateCandidates = simpleDateFormats.stream()
.map(formatter -> tryParse(formatter, dateValue))
.filter(Objects::nonNull)
// check if there is more than one date
.collect(Collectors.toList());
if (dateCandidates.isEmpty()) {
throw new RuntimeException(String.format("Unsupported date format %s", dateValue));
}
if (dateCandidates.size() > 1) {
// check if all dates are the same, otherwise throw exception since your input is ambigious
}
return dateCandidates.get(0);
}
private Date tryParse(SimpleDateFormat formatter, String dateValue) {
try {
return formatter.parse(dateValue);
} catch (ParseException e) {
return null;
}
}

util.sql dates in json response

I'm trying to pass a java util date to my json response without succes.
If i System.out.println the dates i get "1970-01-01 01:00:00.263" correct format.
System.out.println("from date: " + fromDate);
System.out.println("to date: " + toDate);
// from date: 1970-01-01 01:00:00.022
// to date: 1970-01-01 01:00:00.263
// in my json i get
// from date: 22
// to date: 263
if i pass my date to the json return i get " 263 " only (the last part of the timestamp) ?
how can i format the date so i get the whole date (YY-MM-DD, hour-min-sec) instead of just the last part of the timestamp ?
the model object
public class testSomething {
boolean status;
String msg;
Date fromDate;
Date toDate;
public testSomething(boolean status, String msg, Date fromDate, Date toDate) {
this.status = status;
this.msg = msg;
this.fromDate = fromDate;
this.toDate = toDate;
}
the return value
Date fromDate = dates.get(0);
Date toDate = (Date) dates.get(dates.size() - 1);
return new testSomething(true, "msg here", fromDate, toDate);
Something like this will do ...
long timestamp = fromDate.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY/MM/dd HH-mm-ss");
System.out.println(dateFormat.format(timestamp));
fixed it by adding spring.jackson.date-format=(yyyy-MM-dd HH:mm:ss) to my application.properties file
The default conversion is to send the milliseconds since the Epoch (date.getMillis()). There are two reasons for this:
Readability is not a concern for computers.
This time format is independent of the time zone. That means you can send the date to another computer and it will display the same point in time.
Depending on your JSON framework, there are different ways to install data converters. Jackson has several third-party datatype modules for this purpose and you can install your own in your ObjectMapper.
In Java Spring I wanted to send the data & time to a object through a PUT which uses java.sql.Date in the object. I was using json to send it and this is the format I used
public class MyEntityClass {
private String username;
private Date dateTime;
}
And the Json Format I used is,
{
"username": "selena31",
"dateTime":"2017-01-23T12:34:56"
}
And it worked for me :)

convert Date to Time with java

I want to convert a variable of type Date into Time format . I tried to use SimpleDateFormat but without success .
I used the SimpleDateFormat for converting the String into Date.
public static String convDataToString (Date dataconv)
{
SimpleDateFormat formattoData = new SimpleDateFormat("yyyy-MM-dd");
String data = "";
try{
dataconv = formattoData.parse(data);
System.out.println(formattoData.format(dataconv));
}
catch(Exception e){
e.getMessage();
}
return formattoData.format(dataconv);
}
But I need to convert Date into Time format.
In java.util package we can find Date class which encapsulates date and time. If you try new Date(), you get both date and time for the current timestamp. But Calendar class (java.util.Calendar) provides many tools for manipulations of date and time.

Convert Date.toString() back to Date in Java [duplicate]

This question already has answers here:
How to add 10 minutes to my (String) time?
(8 answers)
How can I read and parse a date and time in Android?
(2 answers)
Closed 7 years ago.
I am calling an API and as per the guidelines calling it every time is inefficient as the data does not change that regularly. They recommend calling it once and then not polling until 10 minutes has passed.
I am calling this from an Android app and so I want to store the current date plus 10 minutes. I do this like so:
Date forecastRefreshDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(forecastRefreshDate);
cal.add(Calendar.MINUTE, 10);
editor.putString("ForecastRefreshDate", forecastRefreshDate.toString());
editor.apply();
So now when this code is run again it needs to check if the current time (new Date()) is > the value saved in the cache/app file.
How do I create a Date variable equal to the value stored in the cache as a String?
Convert date to epoch time, which is a number of milliseconds stored as a long. Store long as string and parse back into long when needed.
long epoch = date.getTime(); //where date is your Date
String yourString = Long.toString(epoch); //to string for storage
long time = Long.valueOf(yourString).longValue(); ; //back to epoch
Date originaldate = new Date(Long.parseLong(time)); //back to date
When dealing with time, which is needed only internally to measure time periods,
It is much better to store timestamps as long value (millis sicne 1.1.1970 UTC).
Use long timestamp = System.currentTimeMillis()
If a String storage is neccesary simply convert the Long to a String.
String timeStampStr = String.parseLong(timeStamp);
Do not use Date.toString for other things than for logging or debugging.
The toString() representation may be different in other countries.
If a human readable timestamp string is needed you have to specify a Specific DateFormat, see also DateFormatter.
Parsing a long it the most efficent way, however there may be cases that you have already formatted a date to some other format and want to parse that. Then you should use this
private static final String format = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
private Calendar dateTime = Calendar.getInstance();
public void setDateTime(String dateTimeString) {
try {
dateTime.setTime(formatter.parse(dateTimeString));
} catch (ParseException e) {
// Dummy handled exception
dateTime.setTimeInMillis(0);
}
}
Parse a long containing milliseconds since epoch
Date date = new Date(Long.parseLong(timeInMillisecondsString));
Since you're using a plain toString() it should be coverable using a SimpleDateFormat.
Try this:
DateFormat dateFormat = new SimpleDateFormat();
Date myDate = dateFormat.parse(myDateString);

Java util.numberFormatException for input string: "2014-01-12 05-44-56"

I'm new in OFBiz, and Java. I used bellow block of code for checking date time input and use that for searching in table.
Timestamp strtDate = UtilDateTime.getTimestamp((String)request.getParameter("strt_date"));
if(strtDate != null)
{
// then here i used the date for taking data.
}
When i fill the date time field of form to search or when no date is selected for searching error occure that show numberFormatException, so how i can solve that? thanks for any help and guide.
Based on the Apache ofbiz API it looks like UtilDateTime#getTimestamp(String) expects milliseconds value. You are passing in "2014-01-12 05-44-56". You need to parse your date first. With pure pre 1.8 java (keep in mind that formatters aren't thread safe):
String dateString = "2014-01-12 05-44-56";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date date = formatter.parse(dateString);
UtilDateTime.getTimestamp(date.getTime());
Since java 1.8 (highly recommended to switch if you can!):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
ZonedDateTime date = ZonedDateTime.parse(text, formatter);
long millis = date.toInstant().toEpochMilli();
you have to pass time in milliseconds not as you are passing.
you can check code also :
public static Timestamp getTimestamp(String milliSecs) throws NumberFormatException {
return new Timestamp(Long.parseLong(milliSecs));
}
it will parse the data in long which you are passing and that should be valid long value.
request.getParameter("strt_date") will anyways return String, so no need to cast it explicitly to String. Moreover, there will be a contract between Client & Server on the required Date Format. So you have to parse the String-Date in the same format using SimpleDateFormat. Code outlook will look like bellow:
SimpleDateFormat formatter = new SimpleDateFormat("contract-date-format");
Date date = formatter.parse(request.getParameter("strt_date"));
UtilDateTime.getTimestamp(date.getTime());

Categories

Resources