Convert Date format in Java - java

I have a Date object in DTO object:
public class TopTerminalsDTO {
private Date date;
private int volume;
private int count;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
When I get the response in Angular I get
count: 1
date: "2018-10-06T00:00:00.000+0000"
volume: 111
I want to get this date format YYYY-MM-DD HH:mm:ss in Angular.
What is the proper way to convert the Date into the DTO object? Is it better to use LocalDateTime?

It's better to use LocalDateTime object, but it will return it with a T between the date and hours. You should remove it like in the selected answer here LocalDate - How to remove character 'T' in LocalDate

U can use DateFormat to convert your desire date format.
TopTerminalsDTO tt = new TopTerminalsDTO();
tt.setDate(new Date());
String strDateFormat = "YYYY-MM-DD HH:mm:ss";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(tt.getDate());
System.out.println(formattedDate);
As you are sending rest object to angular so u can use string field as date in DTO once covert it in desire date format.

User the Below Code.
Date myDate = new Date();
System.out.println(new SimpleDateFormat("YYYY-MM-DD HH:mm:ss").format(myDate));

LocalDate is the preferred way of many developers since it's been released in Java 8. You can format a LocalDate object the way you want by using the .format(DateTimeFormatter) method of LocalDate.
Like this example from: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
Edit:
The LocalDate class doens't provide a time representation. Therefore if you like to also have time, use the LocalDateTime class. The .format() method of LocalDateTime can be used like the .format() method of LocalDate as shown above.

Related

Sorting list of data after conversion from string to date

I have below DTO details
public class CreditDetailDTO {
private String sectionType;
private BigDecimal totalAmount;
private List<SectionDetailsDTO> sectionDetails;
}
public class SectionDetailsDTO {
private String startDate;
private String expiryDate;
private BigDecimal amount;
}
I need to sorting sectionDetails by start date. I have use below code for sorting
creditDetailsDTO.getSectionDetails().sort(Comparator.comparing(SectionDetailsDTO::getStartDate));
As you can see that getStartDate is string but what I need, First I
need to convert getStartDate into date and then based on the date
sort the data
Sample Date format : 15-07-2019:11:00:00
Parse the date into LocalDateTime using DateTimeFormatter
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy:HH:mm:ss");
LocalDateTime t = LocalDateTime.parse("15-07-2019:11:10:20",f);
So the sorting code
creditDetailsDTO.getSectionDetails().stream()
.sort(Comparator.comparing(dto -> LocalDateTime.parse(dto.getStartDate(), f)));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(your_String_pattern);
Date date = simpleDateFormat.parse(your_string_value);
Log.e("tag","Converted Date = "+date);
If your value and the pattern matches, it gives you the date. After that you can do your required operations on that date.(Make sure you put some validations for string_date_value).

incompatible types: String cannot be converted to Date

I try to store the current time and date but get the following error:
incompatible types: String cannot be converted to Date
This is the code:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
time.setUpdateDt(dtf.format(now));
public Date getUpdateDt() {
return time;
}
public void setUpdateDt(Date time) {
this.time = time;
}
You are using a DateTimeFormatter to transform a LocalDateTime into a String with DateTimeFormatter.format. Then you send that result as a parameter to setUpdateDt.
public void setUpdateDt(Date time)
The problem is that you send a String instead of a Date.
FYI: you are mixing the time technologies here. Date and LocalDateTIme are two distinct time API, you should not mix those. If you want your POJO to store a date, store it as LocalDateTime.
public void setUpdateDt(LocalDateTime time)
If you really want to get it as a Date from the LocalDateTime, check this answer: Converting between java.time.LocalDateTime and java.util.Date
dtf.format(now) returns a string. not a date object.
if you just want to convert from LocalDate to Date, you could use this method:
LocalDateTime now = LocalDateTime.now();
Date yourDate = Date.from(datetime.atZone(ZoneId.systemDefault()).toInstant());
however if you still need to parse a string, you could inject a parser and assign a date object in your class.
for example:
public class Time {
Date time;
public Date getUpdateDt() {
return time;
}
public void setUpdateDt(Date time) {
this.time = time;
}
//this method will accept a string and inject a date format parser
public void setUpdateDt(String timeStr,DateTimeFormatter dtf) {
LocalDateTime datetime =LocalDateTime.parse(timeStr, dtf);
this.time = Date.from(datetime.atZone(ZoneId.systemDefault()).toInstant());
}
public static void main(String args[]) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
Time time = new Time();
time.setUpdateDt(dtf.format(now),dtf);
System.out.println(time.getUpdateDt());
}
dtf.format(now) will return a String. You are getting the incompatible type error since you are trying to pass this value to the setter which accepts a Date object. Instead of time.setUpdateDt(dtf.format(now));
You could use the java.util.Date class to create a new Date as follows -
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
time.setUpdateDt(dtf.format(now));
public Date getUpdateDt() {
return time;
}
public void setUpdateDt(Date time) {
this.time = time;
}
Or, if you want use the existing LocalDateTime, you can convert it to Date by -
LocalDateTime now = LocalDateTime.now();
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
time.setUpdateDt(dtf.format(date));
initComponents();
jDateChooser.setDate(new Date(fecha()));
//Formato de Fecha
public String fecha() {
Date fecha=new Date();
SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/YYYY", new Locale("es", "EC"));
return formatoFecha.format(fecha);
}

Deserializing with GSON converting java.sql.Date incorrectly

I am using GSON to deserialize a JSON string to a java object. The date in the JSON string is of the format:
yyyy-mm-dd
When the date is read into a java.sql.Date field in my JAVA object, the month always ends up as 01 or january! Very strange.
Here is the code for the JSON String and deserializing with GSON:
public static void main(String[] args)
{
String jsonString = "[{\"date\":\"2015-02-14\"},{\"date\":\"2015-03-15\"},{\"date\":\"2015-04-16\"}]";
Type type = new TypeToken<List<TestObject>>(){}.getType();
Gson gsonReceiver = new GsonBuilder().setDateFormat("yyyy-mm-dd").create();
List<TestObject> objectList = gsonReceiver.fromJson(jsonString, type);
for(int i=0; i < objectList.size(); i++) {
System.out.println("objectList[" + i + "] = " + objectList.get(i).toString());
}
}
And here is the code for the TestObject:
public class TestObject {
private Date date;
public TestObject(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public String toString() {
return "TestObject [date=" + date + "]";
}
}
If you run this piece of code, the dates in the new object get printed out as:
objectList[0] = TestObject [date=2015-01-14]
objectList[1] = TestObject [date=2015-01-15]
objectList[2] = TestObject [date=2015-01-16]
Which is just plain weird.
I think I have set the date format like I should - anybody have any idea what is going wrong here?
The right format is
yyyy-MM-dd
mm stay for minutes. Not months.
Here is the javadoc explaining each letter that can be used in date format functions: link
Infact GSonBuilder uses the same conventions of SimpleDateFormat:
Note that this pattern must abide by the convention provided by SimpleDateFormat class. See the documentation in SimpleDateFormat for more information on valid date and time patterns.

How to get UTC time without SimpleDateFormat? [duplicate]

This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 8 years ago.
I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.
Read up on Joda-Time. That is a better API for such things than the java date and calendar classes
maybe this can help you:
Calendar.getInstance(java.util.TimeZone)
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
java.until.Date does not have a timezone, so there's nothing to be converted. You only see a timezone when you format the date to a string explicitly, or implicitly by using its toString method. An implicit conversion uses the local default timezone.
Internally, Date stores the date/time as a long, representing milliseconds since midnight, Jan. 1, 1970, UTC.
So, if you format a date as a string, and then parse the string back to a date, you've changed nothing at all.
So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.
public class DateTimeHelper {
public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private Date date = new Date();
private final SimpleDateFormat format;
public DateTimeHelper(String dateTimeFormat) {
format = new SimpleDateFormat(dateTimeFormat, Locale.US);
}
public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
this(dateTimeFormat);
try {
format.setTimeZone(timeZoneUTC);
Date utc = format.parse(utcTimeString);
format.setTimeZone(TimeZone.getDefault());
String local = format.format(utc);
date = format.parse(local);
} catch (ParseException e) {
// nothing
}
}
public Date getDate() {
return date;
}
public Date toUtc() {
String temp = toString();
format.setTimeZone(timeZoneUTC);
try {
return format.parse(temp);
} catch (ParseException e) {
return date;
}
}
#Override
public String toString() {
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
public String toUtcString() {
format.setTimeZone(timeZoneUTC);
return format.format(date);
}
}
And another one that's easier to use:
public class MySqlDateTimeHelper extends DateTimeHelper {
public MySqlDateTimeHelper() {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
}
public MySqlDateTimeHelper(String utcTimeString) {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
}
public static String getCurrentTimestampUtc() {
MySqlDateTimeHelper current = new MySqlDateTimeHelper();
return current.toUtcString();
}
}

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.

Categories