DateFormat Pattern for some strings - java

I have some different format of date to parse but I cannot recognize them with SimpleDateFormat. Can anybody help me to find patterns for this dates:
6 July 1892
9 May 1915
February 335
1768-02-12
and
23 september 63 bc
19 august ad 14
Thanks

You just provide possibilities of patterns you want your dates to be parsed by and run through them finding the first matching.
Run solution.

Joda is generally better if you have to parse using multiple formats. For example,
private static DateTimeFormatter dateFormatter;
String[] validDateFormats = new String[] { "dd-MMM-yyyy HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.SSS" };
DateTimeParser[] parsers = new DateTimeParser[validDateFormats.length];
for (int i = 0; i < validDateFormats.length; ++i) {
parsers[i] = DateTimeFormat.forPattern(validDateFormats[i])
.getParser();
}
dateFormatter = new DateTimeFormatterBuilder().append(null, parsers)
.toFormatter().withZone(DateTimeZone.UTC);
Now this dateFormatter will parse correctly if the input matches any of the formats:
inputDate = dateFormatter.parseDateTime(dateStr);
DateTimeFormatter outputFormat = DateTimeFormat
.forPattern("yyyy/MM/dd");
String outputString = inputDate.toString(outputFormat);
The format strings can be looked up from here: http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html

Here you can find a great generator for creating every date format you can imagine
http://www.fileformat.info/tip/java/simpledateformat.htm
E.g. your first both examples are generated with dd MMMM yyyy ;)

Try these
27-May-2012:
System.out.println(new SimpleDateFormat("d-MMM-YYYY").format(new Date()));
27-05-2012 :
System.out.println(new SimpleDateFormat("d-MM-YYYY").format(new Date()));
27-05-12 :
System.out.println(new SimpleDateFormat("dd-MM-YY").format(new Date()));

Related

Generic date parsing in java

I have date strings in various formats like Oct 10 11:05:03 or 12/12/2016 4:30 etc
If I do
// some code...
getDate("Oct 10 11:05:03", "MMM d HH:mm:ss");
// some code ...
The date gets parsed, but I am getting the year as 1970 (since the year is not specified in the string.) But I want the year as current year if year is not specidied. Same applies for all fields.
here is my getDate function:
public Date getDate(dateStr, pattern) {
SimpleDateFormat parser = new SimpleDateFormat(pattern);
Date date = parser.parse(myDate);
return date;
}
can anybody tell me how to do that inside getDate function (because I want a generic solution)?
Thanks in advance!
If you do not know the format in advance, you should list the actual formats you are expecting and then try to parse them. If one fails, try the next one.
Here is an example of how to fill in the default.
You'll end up with something like this:
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("ddMM")
.parseDefaulting(YEAR, currentYear)
.toFormatter();
LocalDate date = LocalDate.parse("yourstring", f);
Or even better, the abovementioned formatter class supports optional elements. Wrap the year specifier in square brackets and the element will be optional. You can then supply a default with parseDefaulting.
Here is an example:
String s1 = "Oct 5 11:05:03";
String s2 = "Oct 5 1996 13:51:56"; // Year supplied
String format = "MMM d [uuuu ]HH:mm:ss";
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern(format)
.parseDefaulting(ChronoField.YEAR, Year.now().getValue())
.toFormatter(Locale.US);
System.out.println(LocalDate.parse(s1, f));
System.out.println(LocalDate.parse(s2, f));
Note: Dates and times are not easy. You should take into consideration that date interpreting is often locale-dependant and this sometimes leads to ambiguity. For example, the date string "05/12/2018" means the 12th of May, 2018 when you are American, but in some European areas it means the 5th of December 2018. You need to be aware of that.
One option would be to concatenate the current year onto the incoming date string, and then parse:
String ts = "Oct 10 11:05:03";
int currYear = Calendar.getInstance().get(Calendar.YEAR);
ts = String.valueOf(currYear) + " " + ts;
Date date = getDate(ts, "yyyy MMM d HH:mm:ss");
System.out.println(date);
Wed Oct 10 11:05:03 CEST 2018
Demo
Note that we could have used StringBuilder above, but the purpose of brevity of code, I used raw string concatenations instead. I also fixed a few typos in your helper method getDate().

Java 8 Timezone conversion when creating java.util.Date [duplicate]

This question already has answers here:
Java program to get the current date without timestamp
(17 answers)
Closed 6 years ago.
I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);
If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So it's behaving exactly as documented.
You've already got a DateFormat with the right format, so you just need to call format on it:
System.out.println("pickUpDate" + sdf.format(pickUpDate));
Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.
As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.
This is the toString() of the java.util.Date
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
So, if you will pass a Date and try to print it this will be printed out all the time.
Code:
Date date = new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
Date : Fri Apr 29 04:53:16 GMT 2016
Sample Output : 2016-04-29
Imports required :
import java.util.Date; //for new Date()
import java.text.SimpleDateFormat; // for the format change
System.out.println("pickUpDate " + sdf.format(pickUpDate));
You can use the above code to get formatted Date as String
Use this Code:
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date pickUpDate =sdf.parse("2007-06-21");
System.out.println("pickUpDate "+sdf.format(pickUpDate));
Hope it'll help you.
String your_format_date=sdf.format(pickUpDate);
System.out.println("pick Up Date " + your_format_date);
Date isn't a date. It's a timestamp. That's some impressive API design, isn't it?
The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.

How do I create the java date object without time stamp [duplicate]

This question already has answers here:
Java program to get the current date without timestamp
(17 answers)
Closed 6 years ago.
I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);
If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So it's behaving exactly as documented.
You've already got a DateFormat with the right format, so you just need to call format on it:
System.out.println("pickUpDate" + sdf.format(pickUpDate));
Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.
As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.
This is the toString() of the java.util.Date
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
So, if you will pass a Date and try to print it this will be printed out all the time.
Code:
Date date = new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
Date : Fri Apr 29 04:53:16 GMT 2016
Sample Output : 2016-04-29
Imports required :
import java.util.Date; //for new Date()
import java.text.SimpleDateFormat; // for the format change
System.out.println("pickUpDate " + sdf.format(pickUpDate));
You can use the above code to get formatted Date as String
Use this Code:
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date pickUpDate =sdf.parse("2007-06-21");
System.out.println("pickUpDate "+sdf.format(pickUpDate));
Hope it'll help you.
String your_format_date=sdf.format(pickUpDate);
System.out.println("pick Up Date " + your_format_date);
Date isn't a date. It's a timestamp. That's some impressive API design, isn't it?
The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.

SimpleDateFormat parsing date string incorrectly

I'm trying to parse a String into a Date and then format that Date into a different String format for outputting.
My date formatting code is as follows:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("d/M/yyyy h:m:s a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
The result of sysObj.getString("document_date") is 1/31/2013 12:00:01 AM. And when I check the value of formattedDocumentDate I get 01/07/2015.
Any help is much appreciated.
You are parsing days 31 as months. SimpleDateFormat tries to give you a valid date. Therefore It adds to 1/0/2013 31 months. This is 2 years and 7 month. So you get your result 01/07/2015. So SimpleDateFormat works correct.
One solution for you is to change your date pattern to M/d/yyyy h:m:s a or your input data.
To avoid these tries you have to switch off SimpleDateFormat lenient mode. Then you will get an exception if the format does not fit.
It looks like your input format is actually months first, then days. So should be "MM/dd/yyyy".
So:
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/M/yyyy");
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDocumentDate = dateFormatter.format(dateParser.parse(sysObj.getString("document_date")));
Another example like this
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
System.out.println("date is:"+new java.sql.Date( sdfInput.parse("20164129").getTime() ));
Output is: 2019-05-29
I expect to throw parse exception but not (41)is not a valid month value.
on the other hand if I gave 20170229, system can recognize the February of 2017 doesn't have a lap year and return 2017-03-01 interesting.

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")));

Categories

Resources