I'm trying to use Joda-Time library to convert a String date and time to Date but the result I get is not the expected.
From the server I get:
08/11/2017 12:30
10/11/2017 12:30
Joda converts it to:
2017-01-08T12:30:00.000+02:00
2017-01-10T12:30:00.000+02:00
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/mm/yyyy HH:mm:ss");
// add two :00 at the end for the seconds
startDate = startDate +":00";
DateTime start = formatter.parseDateTime(startDate);
System.out.println(start.toString());
endDate= endDate + ":00";
DateTime end = formatter.parseDateTime(endDate);
That's because you're using mm for the month, but the correct pattern is uppercase MM. Check the documentation for more details.
One more thing. If your input doesn't have the seconds (:00), you don't need to append it in the end of the input strings. You can simply create a pattern without it:
// "MM" for month, and don't use "ss" for seconds if input doesn't have it
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
// parse input (without ":00" for the seconds)
DateTime start = formatter.parseDateTime("08/11/2017 12:30");
System.out.println(start.toString());
The output will be:
2017-11-08T12:30:00.000-02:00
Notice that the offset (-02:00) is different from yours. That's because DateTime uses the default timezone if you don't specify one.
Related
I want a DateFormatter in java so that i can specify some special character as well as digits in a date expression. For ex :
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
Here dd is used to specify the day of month which is numeric.
But i have a requirement to create a date as below :
String stringDate = "2017-12-??T00:00Z";
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
formatter.parse(stringDate);
I get an unparseable exception as the DAY specified here is ?? . Is there any workaround for this or shall i have to write a new parser ?
Thanks
Try escaping the additional literals using single quote
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-'??T'HH:mm:ss.SSS zzz");
Also the value and the format given should match(Can edit the string date as required), in your case following syntax will work.
String stringDate = "2017-12-??T00:00Z";
Date date = (new SimpleDateFormat("yyyy-MM-'??T'HH:mmZ")).parse(stringDate.replaceAll("Z$", "+0000"));
System.out.println("date: " + (new SimpleDateFormat("yyyy-MM-dd'??T'HH:mmZ")).format(date));
Please note that 'Z' indicates that the timezone conforms to the RFC 822 time zone standard as well.
Edit: Consider a scheduler. Your comment may sound like what you need is a scheduler, for example Quartz scheduler. I include a link at the bottom. Then convert user input not to a YearMonth, OffsetDateTime or any other date-time object (because they don’t fit), but into a syntax that your scheduler can accept.
Original answer
I am giving you a couple of suggestions. It’s with reservation though: I don’t understand why you want this, not even exactly what you want, so these suggestions may not be the right ones for you.
One suggestion I am pretty sure of, though: do use java.time, the modern java date and time API, for your date and time work. It is so much nicer to work with than the old, poorly designed and long outdated date-time classes that include the notoriously troublesome SimpleDateFormat class.
Parsing year and month: If you just want the year and the month from a string that has question marks instead of the day of month, parse into a YearMonth:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-'??T'HH:mmX");
String stringDate = "2017-12-??T00:00Z";
YearMonth ym = YearMonth.parse(stringDate, formatter);
System.out.println("Year and month are " + ym);
Output from this snippet is:
Year and month are 2017-12
Parsing all information from the string: If you need time of day and offset from the same string too, just parse the string once and get the various information from the parse result:
TemporalAccessor parsed = formatter.parse(stringDate);
YearMonth ym = YearMonth.from(parsed);
System.out.println("Year and month are " + ym);
LocalTime time = LocalTime.from(parsed);
System.out.println("Time of day is " + time);
ZoneOffset offset = ZoneOffset.from(parsed);
System.out.println("UTC offset is " + offset);
Year and month are 2017-12
Time of day is 00:00
UTC offset is Z
Using a default day of month: If you know what day of month you want instead of the question marks, specify it as a default value:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-'??T'HH:mmX")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 23)
.toFormatter();
String stringDate = "2017-12-??T00:00Z";
OffsetDateTime dateTime = OffsetDateTime.parse(stringDate, formatter);
System.out.println("Date and time is " + dateTime);
Date and time is 2017-12-23T00:00Z
Accepting both numbers and question marks: If the date can be given as either numeric or question marks, use optional parts in the format pattern strings. Such are enclosed in square brackets:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-[??][dd]'T'HH:mmX")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 23)
.toFormatter();
String stringDate = "2017-12-??T00:00Z";
OffsetDateTime dateTime = OffsetDateTime.parse(stringDate, formatter);
System.out.println("Date and time is " + dateTime);
stringDate = "2018-02-16T00:00Z";
dateTime = OffsetDateTime.parse(stringDate, formatter);
System.out.println("Date and time is " + dateTime);
Date and time is 2017-12-23T00:00Z
Date and time is 2018-02-16T00:00Z
Tutorial links
Cron Trigger Tutorial from the Quartz Scheduler documentation.
Oracle tutorial: Date Time explaining how to use java.time.
I have this date in this format:
String date = "2018-12-08T07:50:00+01:00";
And I'd like to get the local time in this format (adding the hours over GMT) but I'm not able to do it
date = "2018-12-08 08:50:00";
Other example:
String date = "2018-12-08T07:50:00+04:00";
Result:
date = "2018-12-08 11:50:00";
Any help?
As Sun already said in another answer, you misunderstood: 2018-12-08T07:50:00+01:00 is the same point in time as 2018-12-08 06:50:00 in UTC (roughly the same as GMT), not 08:50. +01:00 means that the time comes from a place where the clocks are 1 hour ahead of UTC, so to get the UTC time 1 hour should be subtracted, not added.
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String date = "2018-12-08T07:50:00+01:00";
OffsetDateTime dateTime = OffsetDateTime.parse(date);
OffsetDateTime dateTimeInUtc = dateTime.withOffsetSameInstant(ZoneOffset.UTC);
date = dateTimeInUtc.format(desiredFormatter);
System.out.println(date);
Output from this snippet is:
2018-12-08 06:50:00
Using your other example, 2018-12-08T07:50:00+04:00, the output is
2018-12-08 03:50:00
I am taking advantage of the fact that your string is in ISO 8601 format. OffsetDateTime parses this format as its default, that is, we don’t need to specify the format in a DateTimeFormatter (as we do for your desired result format).
Link: Wikipedia article: ISO 8601
2018-12-08T07:50:00+01:00, the +01:00 in the end does not mean adding hh:mm, it means the datetime is already local date time, in GMT it is 2018-12-08T06:50:00.
You can use string.replaceAll to remove T and +01:00:
String input = "2018-12-08T07:50:00+01:00";
input = input.replaceAll("T", " ");
input = input.replaceAll("\\+.*", "");
System.out.println(input); // 2018-12-08 07:50:00
or parse and re-format it:
OffsetDateTime offsetDateTime = OffsetDateTime.parse("2018-12-08T07:50:00+01:00");
String time = offsetDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).replace("T", " ");
System.out.println(time); // 2018-12-08 07:50:00
I have tried to get the date format 2016-08-29T09:15:17Z but not able to get the trailing Z at the end.
I also checked the date time documentation at official website but could not find a similar pattern. So far the date format I have created is as follows:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
So far the code I have written is:
public static void main(String args[]) throws ParseException{
Date nDate=new Date();
//SimpleDateFormat format=new SimpleDateFormat("ddMMYYYYHHMMSS");
String date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(nDate);
System.out.println(date);
}
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use -
TimeZone timeZone = TimeZone.getTimeZone("UTC"); // optional
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
dateFormat.setTimeZone(timeZone); // optional
String date = dateFormat .format(new Date()); // date will have the required format
System.out.println(date);
Z is a constant value like T in your string, so you have to put single quotes arround it:
String date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(nDate);
If you use Z without single quotes DateFormat expect the timezone value
Oracle Documentation describe that z and Z both are use for time zone.
So if you don't want special meaning of Z then you need to write like :
yyyy-MM-dd'T'HH:mm:ss'Z'
I am adding another way to do it, using the new java.time API introduced from JDK 8 onwards.
LocalDateTime nDate=LocalDateTime.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendLiteral('Z')
.toFormatter();
String date = formatter.format(nDate);
System.out.println(date);
I have this time. 8:32:00 PM. How do I convert this to a 24hr Joda-Time LocalTime format? There's no time converter in the Joda-Time library
Start by parsing the String to a LocalTime...
String timeValue = "8:32:00 PM";
DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("h:mm:ss a").toFormatter();
LocalTime localTime = LocalTime.parse(timeValue, parseFormat);
Then format the result...
DateTimeFormatter outputFormat = new DateTimeFormatterBuilder().appendPattern("H:mm:ss").toFormatter();
String formatted = localTime.toString(outputFormat);
System.out.println(formatted);
Which will output 20:32:00
Remember, the value of LocalTime and the format are two separate concepts, you can't affect the "format" of the LocalTime object itself, you can only translate the concept of the value to a String representation (via a formatter)
If I understand your question,
Once I converted the time to a localtime how do I convert it to its equivalent 24hr format?
You would use DateTimeFormat to create a DateTimeFormatter, like so -
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
String str = fmt.print(dt);
Excerpted from the linked javadoc,
H hour of day (0~23) number 0
m minute of hour number 30
s second of minute number 55
You don't want to convert the time (they're the same time), you want to format the time. Joda has a DateTimeFormatter class (see http://www.joda.org/joda-time/key_format.html for details).
You can use it something like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
String str = date.toString(fmt);
I need to convert a string into a Joda DateTime object, but the code I am using is not doing the conversion correct. My input is 20140722101846-0700, which should convert to something not unlike 2014-07-22T10:18:46-0700. Here is my code, followed by the incorrect output:
String myet = "20140722101846-0700"
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddhhmmss-hhmm");
DateTime mydt = dtf.parseDateTime(myet);
The resulting (incorrect) output is: 2014-07-22T07:00:46.000-07:00
How can I fix the code above so that is outputs a correct date?
Your DateTimeFormat doesn't have the correct symbols.
M is for month
m is for minutes
Z is used for the time zone offset (-0700)
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddhhmmssZ");