util.sql dates in json response - java

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 :)

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;
}
}

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

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

Converting a Date to a new TimeZone in Java

Converting a Java Date object to a specific ("target") time zone is a question that has been asked numerous times before in StackOverflow and the suggested solutions apparently are:
Adjust the time (milliseconds) value of the Date object by the timezone offset
Use SimpleDateFormat (with the timezone) to produce the desired date as a String
However, there seems to be no "plain Java" solution that parses a date string (with or without timezone) into a Date object and then adjusts a corresponding Calendar object to the target timezone, so that the "converted" date behaves in all cases in the correct way (e.g., when using the Calendar object to retrieve the year of the date).
The main issue is that, reasonably, when the SimpleDateFormat pattern used to parse the date string does not have a timezone, the system assumes that the time is in the parsing system's timezone. If, however, the pattern does have a timezone, the time is counted from UTC. So, what is needed is essentially an indication as to whether the original date string corresponds to a pattern with or without a timezone, which apparently cannot be done without analyzing the pattern itself.
The attached source code of the TimezoneDate class demonstrates the discrepancies.
Here is the output from running the main() method for 2 "original dates", the first without and the second with a timezone, when they are converted to UTC on a machine running on Pacific Standard Time (PST):
Original date: 20/12/2012 08:12:24
Formatted date (TZ): 20/12/2012 16:12:24
Formatted date (no TZ): 20/12/2012 08:12:24
Calendar date: 20/12/2012 16:12:24
Expected date: 20/12/2012 08:12:24
Original date: 20/10/2012 08:12:24 +1200
Formatted date (TZ): 19/10/2012 20:12:24
Formatted date (no TZ): 19/10/2012 13:12:24
Calendar date: 19/10/2012 20:12:24
Expected date: 19/10/2012 20:12:24
The correct operation is to have the "Formatted" and "Calendar" strings identical to the "Expected date" for each of the 2 example date strings ("original dates").
Apparently one needs to make a distinction between the case where the date string contains a timezone symbol (TZ) and the case where it does not (no TZ), but this means knowing the SimpleDateFormat pattern beforehand, which is not possible when handling a Date object and not the original string.
So, the question is really about whether a generic "plain Java" (no third party libraries) solution exists that does not require prior knowledge of the pattern and works correctly with the corresponding Calendar object.
Following is the full source code of the TimezoneDate class.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneDate
{
private final Date time;
private final TimeZone timezone;
private final Calendar calendar;
/**
* Creates a wrapper for a {#code Date} object that is converted to the
* specified time zone.
*
* #param date The date to wrap
* #param timezone The timezone to convert to
*/
public TimezoneDate(Date date, TimeZone timezone)
{
this.calendar = TimezoneDate.getPlainCalendar(date, timezone);
this.time = this.calendar.getTime();
this.timezone = timezone;
}
private static Calendar getPlainCalendar(Date date, TimeZone timezone)
{
Calendar calendar = Calendar.getInstance(timezone);
calendar.setTime(date);
return calendar;
}
private static Calendar getAdjustedCalendar(Date date, TimeZone timezone)
{
long time = date.getTime();
time = time + timezone.getOffset(time) - TimeZone.getDefault().getOffset(time);
date = new Date(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public int getYear()
{
return this.calendar.get(Calendar.YEAR);
}
public int getMonth()
{
return (this.calendar.get(Calendar.MONTH)+1);
}
public int getMonthDay()
{
return this.calendar.get(Calendar.DAY_OF_MONTH);
}
public int getHour()
{
return this.calendar.get(Calendar.HOUR_OF_DAY);
}
public int getMinutes()
{
return this.calendar.get(Calendar.MINUTE);
}
public int getSeconds()
{
return this.calendar.get(Calendar.SECOND);
}
public String toCalendarDate() // The date as reported by the Calendar
{
StringBuilder sb = new StringBuilder();
sb.append(this.getMonthDay()).append("/").append(this.getMonth()).
append("/").append(this.getYear()).append(" ").
append(this.getHour()).append(":").append(this.getMinutes()).
append(":").append(this.getSeconds());
return sb.toString();
}
public String toFormattedDate(boolean addTimezone) // The formatted date string
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
if (addTimezone)
{
sdf.setTimeZone(this.timezone);
}
return sdf.format(this.time);
}
public static void main(String[] args) throws Exception
{
// Each data "vector" contains 3 strings, i.e.:
// - Original (example) date
// - SimpleDateFormat pattern
// - Expected date after converting the original date to UTC
String[][] data = new String[][]
{
{"20/12/2012 08:12:24", "dd/MM/yyyy' 'HH:mm:ss", "20/12/2012 08:12:24"},
{"20/10/2012 08:12:24 +1200", "dd/MM/yyyy HH:mm:ss Z", "19/10/2012 20:12:24"}
};
Date originalDate;
TimezoneDate timezoneDate;
SimpleDateFormat format;
TimeZone UTC = TimeZone.getTimeZone("UTC");
for (String[] vector:data)
{
format = new SimpleDateFormat(vector[1]);
originalDate = format.parse(vector[0]);
timezoneDate = new TimezoneDate(originalDate, UTC);
System.out.println();
System.out.println("Original date: " + vector[0]);
System.out.println("Formatted date (TZ): " + timezoneDate.toFormattedDate(true));
System.out.println("Formatted date (no TZ): " + timezoneDate.toFormattedDate(false));
System.out.println("Calendar date: " + timezoneDate.toCalendarDate());
System.out.println("Expected date: " + vector[2]);
}
}
}
Joda-Time
Rather than use Java's Date you should use the Joda-Time DateTime class. This allows you to carry out timezone operations in a very simple fashion, using the withTimezone() and withTimezoneRetainFields() methods depending on your particular requirements.

Cast String to Date

I am developing a Spring/Hibernate web application. I have a DataTranseferObject where the input from the jsp page is stored to be used by different services and eventually saved to a database.
One of the fields in the jsp page is deliveryDate. I want to store it as a date type in the database:
from delivery.java
#Column(name = "DELIVERY_DATE")
private Date deliveryDate;
public void setDeliveryDate(Date deliveryDate){
this.deliveryDate= deliveryDate;
}
public Date getDeliveryDate(){
return deliveryDate;
}
I am trying to validate the field in the jsp page so that only the "yyyy-MM-dd" format is allowed. To do this I have the deliveryDate as a String type in the DataTransferObject and I'm validating it with the #Pattern annotation as such:
#Pattern(regexp="((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])", message="please enter date in fromat yyyy-MM-dd")
#NotNull(message="delivery date is a required field")
private String deliveryDate;
Since I want to store it in the database as a Date type I need to convert the String to a Date type. This I am trying to do using a service:
#Transactional
public Date stringToDateConversion(String stringDate){
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date) formatter.parse(stringDate);
return date;
}
but it's not working since formatter.parse(stringDate) gives "Unhandled exception type ParseException"
I need the service to return a Date type so I can use it in the controller:
Date deliveryDate= deliveryService.stringToDateConversion(deliveryDto.getDeliveryDate());
delivery.setDeliveryDate(deliveryDate);
How do I correctly convert the String to a Date type and return a Date type?
Thanks for the help!
/D
Just handle ParseException with call of parsing String to Date
DateFormat formatter = null;
java.util.Date date = null;
formatter = new SimpleDateFormat("yyyy-MM-dd");
try{
date = formatter.parse(stringDate);
//if you want you can convert it to `java.sql.Date`
}catch(ParseException ex){//do whatever you would like to}
return date;

Retreving date from Hibernate TImestamp

I have a field with temporal type as Timestamp to save both date and time to the database.
#Temporal(TemporalType.TIMESTAMP)
#Column(name="date", nullable=false)
private Date date;
But when displaying the value to the user, I just want to show date part and truncate time part. I tried this but I get ParseException probably because of the Nanosecond part of the Hibernate Timestamp.
SimplDateFormat sd = new SimpleDateFormat("MM/dd/yyyy");
return sd.parse(date.toString());
So how do I retrieve just date from Hibernate Timestamp? Thanks
Just format the date object. The toString method isn't guaranteed to give you a string in a format that can then be parsed.
String dateStr = sd.format(date);
That will give you a date string in MM/dd/yyyy format that you can then convert back into a Date.
Date fancyNancy = sd.parse(dateStr);
* EDIT *
Run this code and verify it prints out the day, month and year with no time.
try {
Date d = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Date: " + d);
System.out.println("Formatted Date: " + df.parse(df.format(d)));
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources