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.
Related
I have to convert
"fromTime" : "04-10-2021"`
to
"fromTime" : "2021-10-04T00:00:00.000"
and
"toTime" : "06-10-2021"
to
"toTime" : "2021-10-06T23:59:59.000"
in java . Help please!
Generally speaking, you really want to avoid representing date/time as String where ever possible.
Displaying date/time values to the user should be done in styles that respect their localisation and transmitting date/time values using JSON or XML should use common/standardised formats. This reduces a LOT of issues (don't even get me started)
For example, had I the choice, I would prefer to use ISO_LOCAL_DATE (uuuu-MM-dd) and ISO_LOCAL_DATE_TIME (uuuu-MM-dd'T'HH:mm:ss). I'm already worried about the lack of time zone information 😱
A "simple" approach might be to do something like...
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu.SSS");
LocalDateTime locatDateTime = LocalDate
.parse("04-10-2021", dateFormatter)
.atTime(0, 0, 0, 0);
String dateAndTime = locatDateTime.format(timeFormatter);
System.out.println(dateAndTime);
locatDateTime = LocalDate
.parse("04-10-2021", dateFormatter)
.atTime(23, 59, 59, 0);
dateAndTime = locatDateTime.format(timeFormatter);
System.out.println(dateAndTime);
Basically...
Parse the date value through a DateTimeFormatter using a matching format patten
Convert the LocalDate to a LocalDateTime by passing in the values we want to use
Format the LocalDateTime through a DateTimeFormatter to the desired format
which prints...
04-10-2021T00:00:00.000
06-10-2021T23:59:59.000
See:
The date/time trail
Introduction to the Java 8 Date/Time API
for more details
Now, if all you really want to do, is make it "start of" and "end of" day, you might be able to use...
LocalDateTime startOfDay = LocalDate
.parse("04-10-2021", dateFormatter)
.atStartOfDay();
LocalDateTime endOfDay = LocalDate
.parse("06-10-2021", dateFormatter)
.plusDays(1)
.atStartOfDay()
.minusSeconds(1);
Right about now, I'd be starting a utility class of some kind which had a method which could take a date String (and possibly an optional format) and generate a LocalDate and then another method which could take LocalDate which could convert it to a LocalDateTime at either the startOfDay or endOfDay
You have to do these steps:
create a DateTimeFormatter for dd-MM-yyyy
parse the date with LocalDate.parse with atTime
create a DateTimeFormatter for yyyy-MM-dd'T'HH:mm:ss.SSS
format the date in order to have the final result
public String changeFormatDate(String date, int hour, int minute, int second, int nanoOfSecond) {
DateTimeFormatter formatterFrom = DateTimeFormatter.ofPattern("dd-MM-yyyy"); // 1
LocalDateTime localDateTimeFrom = LocalDate.parse(date, formatterFrom).atTime(hour, minute, second, nanoOfSecond); // 2
DateTimeFormatter formatterTo = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); // 3
return localDateTimeFrom.format(formatterTo); //4
}
Call example:
String fromTime = changeFormatDate("04-10-2021", 0, 0, 0, 0);
String toTime = changeFormatDate("06-10-2021", 23, 59, 59, 999999999);
Here's an example using java.time:
public static void main(String[] args) {
// input dates / days
String fromDate = "04-10-2021";
String toDate = "06-10-2021";
// prepare the times of day
LocalTime startOfDay = LocalTime.MIN; // 00:00:00.000
LocalTime endOfDay = LocalTime.of(23, 59, 59); // 23:59:59.000
// create an object that takes care of parsing the expected format
DateTimeFormatter customDateParser = DateTimeFormatter.ofPattern("dd-MM-uuuu");
// then parse the dates using the formatter / parser
LocalDate fromDay = LocalDate.parse(fromDate, customDateParser);
LocalDate toDay = LocalDate.parse(toDate, customDateParser);
// then concatenate the parsed dates with the prepared times of day
LocalDateTime fromTime = LocalDateTime.of(fromDay, startOfDay);
LocalDateTime toTime = LocalDateTime.of(toDay, endOfDay);
// finally define a formatter for the String output of the LocalDateTimes
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
// and print their toString() methods
System.out.println("from " + fromTime.format(customFormatter)
+ " to " + toTime.format(customFormatter));
}
from 2021-10-04T00:00:00.000 to 2021-10-06T23:59:59.000
String date = "08/02/2022 Tuesday";
DateTimeFormatter LONG_DATE_FORMAT_ddMMyyyyEEEE = ofPattern("dd/MM/yyyy EEEE");
LocalDate.parse(date, LONG_DATE_FORMAT_ddMMyyyyEEEE);
I'm getting a DateTimeParseException with the following message: Text 08/02/2022 Tuesday' could not be parsed at index 11.
I suppose this is an issue with the EEEE side of my format, but I can't seem to understand what should replace it.
This is java 1.8.0_311
We need DateTimeFormatter class to format date string properly. We also need to convert the string date to LocalDate object and back to string again to display. The DateTimeParseException class handles any undesired outcomes.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class Main {
public static void main(String[] args) {
try{
String date = "08-02-2022 Tuesday";
DateTimeFormatter pattern =
DateTimeFormatter.ofPattern("dd-MM-yyyy eeee");
// parsing string date to LocalDate obj
// The part you were missing
LocalDate formattedDate = LocalDate.parse(date, pattern);
// Again converting to string
System.out.println(formattedDate.format(pattern));
}
// handling exception for unparseble dates
catch(DateTimeParseException x){
System.out.println("The given date cannot be parsed");
}
}
}
LocalDate contains of a day, month, and year (Variation between +999999999-12-31 and -999999999-12-31)
Things like time and other values are rejected by the parsing. If you would like the day of the week, you can use a function like:
// Parses the date
LocalDate dt = LocalDate.parse("2018-11-27");
// Prints the day
System.out.println(dt.getDayOfWeek());
This works for me:
String date = "08/02/2022 Tuesday";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy EEEE");
LocalDate time = LocalDate.parse(date, formatter);
System.out.println(time.format(formatter));
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) {
}
I have very simple question - I read couple of threads here but I still do not understand how to get simple thing. I want to send string to method and get back joda date. I had no problem to build it up, but return format is 2015-03-11T17:13:09:000+01:00. How can I get desired (e.g. mmm-dd hh:mm) format back from below mentioned method (it mustto be a dateTime for sorting purposes on FX form)? I tried to gamble with another dateTimeFormatter but had no luck. Thank you very much in advance
public static DateTime stringToDateTime(String textDate) throws ParseException
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
DateTime jodaTime = dateTimeFormatter.parseDateTime(textDate);
return jodaTime;
}
What do you mean by "return format"? "Format" term here could only be related to a string representation of a DateTime object. That means you should specify format of your input string (what you've already done in your code) - and a corresponding DateTime object will be created. After that you probably use toString() to check the results, but DateTime.toString() uses ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ) according to JavaDoc - that gives you your 2015-03-11T17:13:09:000+01:00 result.
So to get it as desired you could try using toString(String pattern) method with format you need. But once again - it's just an output format to convert DateTime to String, it doesn't affect the datetime stored in your DateTime object.
I just use Calendar object so this is a possible way to do it:
static String stringToDateTime(String textDate) {
Calendar c = new GregorianCalendar();
// How you want the input to be formatted
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = df.parse(textDate);
c.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
// How do you want to print your date
df= new SimpleDateFormat("dd-MM-yy");
return df.format(c.getTime());
}
// input
String myDate = "2015-04-15 14:25:25";
System.out.println(stringToDateTime(myDate));
In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);