"How to format LocalDate with Custom Pattern" in Java - java

I am new to JodaTime and learning it to my own. Actually what I want is to just format the LocateDate in my own format. My format is "dd-mm-yyyy"
I have method that calculates the difference with two dates:
private void sampleDaysDifference() {
DateTime todayDate = getLocalTodayDate();
DateTime dateAfterTwoDays = getDateAfterTwoDays();
//get the days difference
int differenceOfDates = Days.daysBetween(todayDate, dateAfterTwoDays).getDays();
Log.e("logX","differenceOfDates: " + differenceOfDates);
}
To get the today date I am using:
private DateTime getLocalTodayDate() {
LocalDate now = LocalDate.now();
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_FORMAT);
return fmt.parseDateTime(now.toString());//return the today date
}
and to get the date after two days:
private DateTime getDateAfterTwoDays() {
LocalDate now = LocalDate.now();
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_FORMAT);
return fmt.parseDateTime(now.plusDays(2).toString());//return date after two days
}
The problem is that I have no idea how to format date using JodaTime, can somebody please tell me how to format a JodaTime LocalDate!
Actually my app is crashing with the stacktrace:
Caused by: java.lang.IllegalArgumentException: Invalid format: "16 January, 2019" is malformed at " January, 2019"

You are almost there but just the pattern is wrong that you specified, change "dd-mm-yyyy" to this "dd-MM-yyyy" docs-for-patterns
Simple Example
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))); //16-01-2019
From Joda DateTimeFormatter joda-docs
The pattern syntax is mostly compatible with java.text.SimpleDateFormat

Related

How to find a Future Date in Java(say two months from today) in 24 February 2019 format

Below is the approach I am going with :
Date DateObject = new Date();
SimpleDateFormat formatDate = new SimpleDateFormat("dd MMMM yyyy");
String dateString = formatDate.format(DateObject);
System.out.println(dateString);
Now this gives me the current date in desired format. I want to find the Value of Date in same format exactly two months from this date.
I also tried to work with below approach :
LocalDate futureDate = LocalDate.now().plusMonths(2);
This gives me the date I want which is two months from now but in 2019-04-24 format. When I tried to format this date using SimpleDateFormat it is giving me Illegal Argument Exception.
Try using the DateTimeFormatter class introduced in Java 8, avoid using the SimpleDateFormat :
public static void main(String[] args) {
LocalDate futureDate = LocalDate.now().plusMonths(2);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy");
String dateStr = futureDate.format(formatter);
System.out.println(dateStr);
}
Output:
24 April 2019
The DateTimeFormatter in Java 8 is immutable and thread-safe alternative to SimpleDateFormat.

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

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

How to format Joda-Time DateTime to only mm/dd/yyyy?

I have a string "11/15/2013 08:00:00", I want to format it to "11/15/2013", what is the correct DateTimeFormatter pattern?
I've tried many and googled and still unable to find the correct pattern.
edit: I am looking for Joda-Time DateTimeFormatter, not Java's SimpleDateFormat..
Note that in JAVA SE 8 a new java.time (JSR-310) package was introduced. This replaces Joda time, Joda users are advised to migrate. For the JAVA SE ≥ 8 way of formatting date and time, see below.
Joda time
Create a DateTimeFormatter using DateTimeFormat.forPattern(String)
Using Joda time you would do it like this:
String dateTime = "11/15/2013 08:00:00";
// Format for input
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");
// Printing the date
System.out.println(dtfOut.print(jodatime));
Standard Java ≥ 8
Java 8 introduced a new Date and Time library, making it easier to deal with dates and times. If you want to use standard Java version 8 or beyond, you would use a DateTimeFormatter. Since you don't have a time zone in your String, a java.time.LocalDateTime or a LocalDate, otherwise the time zoned varieties ZonedDateTime and ZonedDate could be used.
// Format for input
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
LocalDate date = LocalDate.parse(dateTime, inputFormat);
// Format for output
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
// Printing the date
System.out.println(date.format(outputFormat));
Standard Java < 8
Before Java 8, you would use the a SimpleDateFormat and java.util.Date
String dateTime = "11/15/2013 08:00:00";
// Format for input
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Parsing the date
Date date7 = dateParser.parse(dateTime);
// Format for output
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
// Printing the date
System.out.println(dateFormatter.format(date7));
I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:
dateTime.toString(DateTimeFormat.longDate());
This is most of the options printed out with their format:
shortDate: 11/3/16
shortDateTime: 11/3/16 4:25 AM
mediumDate: Nov 3, 2016
mediumDateTime: Nov 3, 2016 4:25:35 AM
longDate: November 3, 2016
longDateTime: November 3, 2016 4:25:35 AM MDT
fullDate: Thursday, November 3, 2016
fullDateTime: Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time
DateTime date = DateTime.now().withTimeAtStartOfDay();
date.toString("HH:mm:ss")
I think this will work, if you are using JodaTime:
String strDateTime = "11/15/2013 08:00:00";
DateTime dateTime = DateTime.parse(strDateTime);
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/YYYY");
String strDateOnly = fmt.print(dateTime);
I got part of this from here.
I have a very dumb but working option.
if you have the String fullDate = "11/15/2013 08:00:00";
String finalDate = fullDate.split(" ")[0];
That should work easy and fast. :)
Please try to this one
public void Method(Datetime time)
{
time.toString("yyyy-MM-dd'T'HH:mm:ss"));
}
UPDATED:
You can: create a constant:
private static final DateTimeFormatter DATE_FORMATTER_YYYY_MM_DD =
DateTimeFormat.forPattern("yyyy-MM-dd"); // or whatever pattern that you need.
This DateTimeFormat is importing from: (be careful with that)
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
Parse the Date with:
DateTime.parse(dateTimeScheduled.toString(), DATE_FORMATTER_YYYY_MM_DD);
Before:
DateTime.parse("201711201515",DateTimeFormat.forPattern("yyyyMMddHHmm")).toString("yyyyMMdd");
if want datetime:
DateTime.parse("201711201515", DateTimeFormat.forPattern("yyyyMMddHHmm")).withTimeAtStartOfDay();
This works
String x = "22/06/2012";
String y = "25/10/2014";
String datestart = x;
String datestop = y;
//DateTimeFormatter format = DateTimeFormat.forPattern("dd/mm/yyyy");
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(datestart);
d2 = format.parse(datestop);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
//Period
period = new Period (dt1,dt2);
//calculate days
int days = Days.daysBetween(dt1, dt2).getDays();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Another way of doing that is:
String date = dateAndTime.substring(0, dateAndTime.indexOf(" "));
I'm not exactly certain, but I think this might be faster/use less memory than using the .split() method.
easiest way:
DateTime date = new DateTime();
System.out.println(date.toString(DateTimeFormat.forPattern("yyyy-mm-dd")));

Calendar date to yyyy-MM-dd format in java

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

Converting Epoch time to date string

I have seen this question asked multiple times and none of the answers seem to be what i need.
I have a long type variable which has an epoch time stored in it.
What i want to do is convert it to a String
for example if the epoch time stored was for today the final string would read:
17/03/2012
How would i to this?
Look into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.format(new Date(myTimeAsLong));
You'd create a Date from the long - that's easy:
Date date = new Date(epochTime);
Note that epochTime here ought to be in milliseconds since the epoch - if you've got seconds since the epoch, multiply by 1000.
Then you'd create a SimpleDateFormat specifying the relevant pattern, culture and time zone. For example:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
format.setTimeZone(...);
Then use that to format the date to a string:
String text = format.format(date);
Date date = new Date(String);
this is deprecated.
solution
Date date = new Date(1406178443 * 1000L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
make sure multiply by 1000L
If the method should be portable, better use the default (local time) TimeZone.getDefault():
String epochToIso8601(long time) {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(new Date(time * 1000));
}
try this
Date date = new Date(1476126532838L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
format.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));//your zone
formatted = format.format(date);
System.out.println(formatted);
Joda-Time
If by epoch time you meant a count of milliseconds since first moment of 1970 in UTC, then here is some example code using the Joda-Time library…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( yourMilliseconds, timeZone );
String output = DateTimeFormat.forStyle( "S-" ).withLocale( Locale.CANADA_FRENCH ).print( dateTime );
Other Epochs
That definition of epoch is common because of its use within Unix. But be aware that at least a couple dozen epoch definitions are used by various computer systems.
Time for someone to provide the modern answer (valid and recommended since 2014).
java.time
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.US);
String facebookTime = "1548410106047";
long fbt = Long.parseLong(facebookTime);
ZonedDateTime dateTime = Instant.ofEpochMilli(fbt).atZone(ZoneId.of("America/Indiana/Knox"));
System.out.println(dateTime.format(formatter));
The output is:
January 25, 2019 at 3:55:06 AM CST
If you wanted only the date and in a shorter format, use for example
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.US);
1/25/19
Note how the snippet allows you to specify time zone, language (locale) and how long or short of a format you want.
Links
Oracle tutorial: Date Time explaining how to use java.time.
My example string was taken from this duplicate question
Try this...
sample Epoch timestamp is 1414492391238
Method:
public static String GetHumanReadableDate(long epochSec, String dateFormatStr) {
Date date = new Date(epochSec * 1000);
SimpleDateFormat format = new SimpleDateFormat(dateFormatStr,
Locale.getDefault());
return format.format(date);
}
Usability:
long timestamp = Long.parseLong(engTime) / 1000;
String engTime_ = GetHumanReadableDate(timestamp, "dd-MM-yyyy HH:mm:ss aa");
Result:
28-10-2014 16:03:11 pm
You need to be aware that epoch time in java is in milliseconds, while what you are converting may be in seconds. Ensure that both sides of the conversions are in milliseconds, and then you can fetch the date parameters from the Date object.
ArLiteDTMConv Utility help converting EPOUCH-UNIX Date-Time values, Form EPOUCH-UNIX-To-Date-format and Vise-Versa. You can set the result to a variable and then use the variable in your script or when passing as parameter or introduce in any DB criteria for both Window and Linux. (Download a zip file on this link)

Categories

Resources