joda time formatter parsing yyyy-mm-dd with extra hour - java

I'm using Joda time DateTimeFormatter to create a new datetime object in yyyy-mm-dd string format. When calling DateTime date = formatter.parse(String) I get a DateTime object with an extra hour. I live in UTC +1. How to format a string datetime without hours added.
String date = "2013-01-28";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-mm-dd");
DateTime date = formatter.parseDateTime(date);
date.ToString() = 2013-01-28T00:01:00.000+01:00
expected = 2013-01-28T00:00:00.000+01:00
Additionally, later in the code I compare two DateTime objects. This parser is in yymmdd format and it does not add one hour.
String date = "130102"
DateTimeFormatter format = DateTimeFormat.forPattern("yyMMdd");
DateTime datetime = format.parseDateTime(date);
datetime.toString = 2013-01-02T00:00:00.000+01:00

yyyy-mm-dd uses the minute-of-hour, not the month (pattern symbol M). Please refer to the documentation of pattern symbols on Joda-Time-page.
Parsing "2013-01-28" with your wrong pattern yields "2013-01-28T00:01:00.000+01:00". Do you see the minute equal to 1? And the month of January seems to be a default value if the parser cannot find a month information (in my opinion not smart).

Related

Get 1 year back dateTime from current dateTime in yyyy-MM-dd HH:mm:ss.SSS format

I need to get the datetime of 1 year back considering the current datetime. The format needed to be in "yyyy-MM-dd HH:mm:ss.SSS"
ex : 2019-08-13 12:00:14.326
I tried following. But getting an error.
LocalDate now = LocalDate.now();
LocalDate localDate = LocalDate.parse(now.toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")).minusYears(1);
Below Exception returned:
DateTimeParseException: Text '2020-08-13' could not be parsed
What's the best way to do this in Java 8+ ?
A LocalDate does not hold any information about hours, minutes, seconds or any unit below, instead, it holds information about year, month and day. By calling LocalDate.now() you are getting the date of today (the day of code execution).
If you need the time as well, use a LocalDateTime, which has a method now(), too, and actually consists of a LocalDate and a LocalTime.
Your error message tells you that the content of a LocalDate cannot be formatted using the given pattern (-String) "yyyy-MM-dd HH:mm:ss.SSS" because that pattern requires values for hours (HH), minutes (mm), seconds (ss) and milliseconds (SSS are fraction of seconds and three of them make it be milliseconds).
For parsing Strings or formatting datetimes, a LocalDateTime may be suitable but if you want to reliably add or subtract a year or any other amount of time, you'd rather use a class that considers time zones, offsets and daylight saving like ZonedDateTime or OffsetDateTime...
The LocalDate is the wrong class for your requirement as it does not hold the time information. You can use LocalDateTime but I suggest you use OffsetDateTime or ZonedDateTime so that you can get the flexibility of using the Zone Offset and Zone ID. Check https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html for an overview of date-time classes.
Also, keep in mind that a date or time or date-time object is an object that just holds the information about date/time; it doesn't hold any information about formatting and therefore no matter what you do when you print their objects, you will always get the output what their toString() methods return. In order to format these classes or in other words, to get a string representing a custom format of these objects, you have formatting API (e.g. the modern DateTimeFormatter or legacy SimpleDateFormat) at your disposal.
A sample code:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Get the current date & time at UTC
OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println("Now at UTC: " + odtNow);
// Get the date & time one year ago from now at UTC
OffsetDateTime odtOneYearAgo = odtNow.minusYears(1);
System.out.println("One year ago at UTC: " + odtNow);
// Define a formatter for the output in the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
// Format the date & time using your defined formatter
String formattedDateTimeOneYearAgo = formatter.format(odtOneYearAgo);
System.out.println("Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: " + formattedDateTimeOneYearAgo);
}
}
Output:
Now at UTC: 2020-08-13T08:50:36.277895Z
One year ago at UTC: 2020-08-13T08:50:36.277895Z
Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: 2019-08-13 08:50:36.277
May not be the best way, but this will do it
LocalDateTime date = LocalDateTime.now().minusYears(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(date.format(formatter));
You say you want date+time from 1 year back, but you give it only a date (LocalDate). If you just want the date, all you need to do is:
LocalDate now = LocalDate.now();
LocalDate then = now.minusYears(1);
And if you want the timestamp also, then:
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusYears(1);
And so on for other objects.
As mentioned you should use LocalDateTime instead of LocalDate.
Your exception was thrown because your input String is in ISO_DATE_TIME format
Java Doc
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String now = dateTimeFormatter.format(LocalDateTime.now());
LocalDateTime localDate = LocalDateTime.parse(now, dateTimeFormatter);

Converting from String to specific HH:mm date format

I have a String object which stores the current system time in HH:mm format. I have to convert this to a DATE object and maintain the same HH:mm format. How can this be done.
I tried using Date parse options but everytime I get the response in complete dd-MM-yyyy HH:mm:ss format and not in the required HH:mm format needed.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String getCurrentTime = sdf.format(Calendar.getInstance().getTime());
Date date = sdf1.parse(getCurrentTime);
Expected output should be a Date result in HH:mm format.
Like mentioned in the comments, Date is an object. Other way around with Date/Time API:
LocalTime time = LocalTime.now(); //current time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); //set format
System.out.println(time.format(formatter));
Here is the simple example to solve this using java8 Date and Time API:
DateTimeFormatter parser1 = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime ldd1 = LocalDateTime.now();
System.out.println("DateTimeFormatter ldd1 = " + parser1.format(ldd1));
You are expecting the output of parse to be a Date object in format HH:mm but this will never be the case because it is eventually a Date object. It will have information of date,month,year, time etc i.e. it is made to store both date and time information.
You get the information HH:mm using the format method which you did and it does give you that information
If you want only information of Hour and minutes, I suggest you to create a new class and populate it's value based on output of format method
Instead of using Date use java.time.LocalTime. Example:
LocalTime localTime = LocalTime.now();
This class does not store and represent a date or time-zone. You can use the LocalTime.now() and LocalTime.of() methods to create the current time and specific time object respectively.
You can use the getHour(), getMinute() and getSecond() methods of the LocalTime class to get hour, minute and second respectively.
You can use the plus and minus methods of the LocalTime class to add or subtract hours, minutes etc.
You can use the compareTo(), isAfter() and isBefore() methods of the LocalTime class to compare the LocalTime objects.

How to convert a string date to a different timezone using Java 8 [duplicate]

I want to convert a String Date into a DateTime object for a particular timezone and in a particular format. How can I do it ?
String Date can be in any format used in the world. Example MM-DD-YYYY, YYYY-MM-DD, MM/DD/YY
, MM/DD/YYYY etc. TimeZone can be any legal timezone specified by the user.
Example - convert YYYY-MM-DD into MM/DD/YY for the Pacific Timezone.
Use DateTimeFormatterBuilder to build a formatter that is able to parse/format multiple DateTimeFormats, and set the resulting DateTimeFormatter to use a specified DateTimeZone:
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("MM-dd-yyyy").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
DateTimeFormat.forPattern("MM/dd/yyyy").getParser(),
DateTimeFormat.forPattern("yyyy/MM/dd").getParser()
};
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(null, parsers)
.toFormatter()
.withZone(DateTimeZone.UTC);
DateTime dttm1 = formatter.parseDateTime("01-31-2012");
DateTime dttm2 = formatter.parseDateTime("01/31/2012");
DateTime dttm3 = formatter.parseDateTime("2012-01-31");
To format a given DateTime you can just use dttm1.toString("yyyy-MM-dd")).

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Easiest way to parse date in String format to GregorianCalendar

I have the following date:
2011-10-07T08:51:52.006Z
Now I want to parse it into a GregorianCalendar. Is there an easier way to do it than using substrings and parsing them to Integers?
And what is the Z in the time string?
I tried to parse it using SimpleDateFormat, but I can´t find a explanation for the T in the date String.
DateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" )
Date date = format.parse( "2011-10-07T08:51:52.006Z" );
Calendar calendar = new GregorianCalendar();
calendar.setTime( date );
I would take a look at DateTimeFormatter
DateTimeFormatter formatter =
DateTimeFormat.forPattern("<custom_pattern>").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("<your_input>");
GregorianCalendar cal = dateTime.toGregorianCalendar();
The T in your string acts as a separator between the date and the time and the Z is the time-zone information both as per ISO-8601 format.
You could use the SimpleDateFormatter to parse the String. Please read the javadoc for the aforementioned class to know what could be the format string. 'Z' indicates the timezone information.

Categories

Resources