How to format your SimpleDateFormat output - java

Below, I've got a chunk of code that returns a date in the format of "Sat May 02 00:00:00 MST 1970" (assuming it receives an input of 05/02). How do I format this so that I've just got "May 02"? It doesn't matter to me if I format it here in this block of code or in my print statement.
My current print statement is System.out.print(Date.getAlphabetDate().
public static Date getAlphabetDate()
{
try
{
String tempDate = month + "/" + day;
Date alphabetDate = new SimpleDateFormat("M/d").parse(tempDate);
return alphabetDate;
}
catch(Exception e)
{
return null;
}
}

You are misunderstanding what SDF does. It returns a Date object, not the String representation of that object. And while a Date object has all that baggage that you're not interested in, you shouldn't care too much about it, since to get a similar String representation of the Date returned, simply use the same or a similar SDF object and use it to format the date:
String stringRep = mySDF.format(myDate);
As an aside, note that whenever code is written with a catch block that returns null, a puppy dies somewhere.
Edit
For example,
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SdfFun {
private static final String PATTERN = "MM/dd";
private static final SimpleDateFormat SDF = new SimpleDateFormat(PATTERN);
public static Date getAlphaDate(int month, int day) throws ParseException {
String tempDate = month + "/" + day;
return SDF.parse(tempDate);
}
public static void main(String[] args) {
Date date = null;
try {
date = getAlphaDate(2, 16);
System.out.println(SDF.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Related

Parser pattern for monthOfYear that is not zero-padded with no literal text separation

Is it possible to parse the date 8302011 using jodatime? In a less painful format, it would look like 8/30/2011, which I would pattern as MM/dd/yyyy.
What I've tried:
Pattern Mddyyyy
8302011 -> Cannot parse "8302011": Value 83 for monthOfYear must be in the range [1,12]
12302011 -> 2011-12-30T00:00:00.000Z
Fortunately, the date is not ambiguous as day is always represented as two digits. Month, however, is either one or two digits.
I realize that it would be simple enough to pad zeros on the left to 8 characters, but in this case, I am unable to do that.
I know the below is different from jodatime but can you try to use SimpleDateFormat to parse the date as an alternative one
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by luan on 9/12/16.
*/
public class DateTimeFormatTest {
public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("Mddyyyy");
public SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("MM/dd/yyyy");
public Date getDate(String source){
Date date = null;
try {
date = simpleDateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public String parseStringValue(Date date){
String result = "";
result = simpleDateFormat2.format(date);
return result;
}
public static void main(String[] args) {
DateTimeFormatTest obj = new DateTimeFormatTest();
Date date = obj.getDate("8302011");
System.out.println(date);
String result = obj.parseStringValue(date);
System.out.println(result);
}
}
Output:
Tue Aug 30 00:00:00 ICT 2011
08/30/2011

converting string to date and converting date back to string

Hi for some of the requirement i need to convert the string representation of date(with no format) to date object and convert back to string(with a specific format)
This is what i tried so far, the output is not coming as expected and it's printing something like 08140009 - Any idea what is this
And please provide any suggestions.
MY code is :
public String getDateBackToCST(String createDate){
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMddyyyy");
TimeZone obj = TimeZone.getTimeZone("CST");
dateFormatter.setTimeZone(obj);
Date createdDate = null;
try {
createdDate = dateFormatter.parse(createDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormatter.format(createdDate);
}
You need to specific proper flags for SimpleDateFormat. You have 2 options to specify timezone z and Z and to specify day name use E like this
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws ParseException {
String date = "Sat Sep 20 23:39:04 IST 2014 ";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
System.out.println(sdf.parse(date));
}
}

How to reformat a string date in Java

I tacked this problem in VB awhile back, and thought I could easily translate it to Java. The input comes in as a string in the format:
"mm/dd/yyyy"
I want to change this to the following format:
"mm/dd/yy"
where the last two year digits are shown only. I wrote this VB awhile back, which does just that:
Function DateFormat(ByVal myDate As String) As String
Dim reformat As Date
reformat = Date.Parse(myDate, Nothing)
Return Format(reformat, "MM/dd/yy").ToString()
End Function
How can I do this exact same thing in Java, so that the date is reformatted correctly and returned as the string it originally was? I have something like this but it is not working properly:
public static String DateFormat(String myDate){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try{
Date formattedDate = formatter.parse(myDate);
return formattedDate.toString();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
I am not sure how to make it the format I need, as I can't find anything similar to the Format() function VB has. Thanks in advance.
Try this :
public static String DateFormat(String myDate) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outFormat = new SimpleDateFormat("MM/dd/yy");
Date parsedInDate = inFormat.parse(myDate);
return outFormat.format(parsedInDate);
}
At start, we declare two date formatters, then we create Date object from input String, and at the end we produce String in new format.
If I understand your question, you could use a pair of SimpleDateFormat(s)
private static final String formatIn = "MM/dd/yyyy";
private static final String formatOut = "MM/dd/yy";
private static final DateFormat sdfIn = new SimpleDateFormat(
formatIn);
private static final DateFormat sdfOut = new SimpleDateFormat(
formatOut);
public static String formatDateString(String dateIn)
throws ParseException {
return sdfOut.format(sdfIn.parse(dateIn));
}
public static void main(String[] args) {
try {
System.out.println(formatDateString("07/15/2014"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
07/15/14
SimpleDateFormat takes in a number of different formats. I believe the format you want is already built in and can be accessed like so...
Date date = new Date();
Format formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
You've basically almost got it, just need to apply the new format.
public static String DateFormat(String myDate){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try{
Date date = formatter.parse(myDate);
formatter.applyPattern("MM/dd/yy");
return formatter.format(date);
}catch(Exception e){
e.printStackTrace();
return null;
}
}

SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?

Here is an example:
public MyDate() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
String t1 = "2011/12/12aaa";
System.out.println(sdf.parse(t1));
}
2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.
Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?
The JavaDoc on parse(...) states the following:
parsing does not necessarily use all characters up to the end of the string
It seems like you can't make SimpleDateFormat throw an exception, but you can do the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";
System.out.println(sdf.parse(t1,p));
if(p.getIndex() < t1.length()) {
throw new ParseException( t1, p.getIndex() );
}
Basically, you check whether the parse consumed the entire string and if not you have invalid input.
To chack whether a date is valid
The following method returns if the date is in valid otherwise it will return false.
public boolean isValidDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
Date testDate = null;
try {
testDate = sdf.parse(date);
}
catch (ParseException e) {
return false;
}
if (!sdf.format(testDate).equals(date)) {
return false;
}
return true;
}
Have a look on the following class which can check whether the date is valid or not
** Sample Example**
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateValidCheck {
public static void main(String[] args) {
if(new DateValidCheck().isValidDate("2011/12/12aaa")){
System.out.println("...date is valid");
}else{
System.out.println("...date is invalid...");
}
}
public boolean isValidDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
Date testDate = null;
try {
testDate = sdf.parse(date);
}
catch (ParseException e) {
return false;
}
if (!sdf.format(testDate).equals(date)) {
return false;
}
return true;
}
}
Java 8 LocalDate may be used:
public static boolean isDate(String date) {
try {
LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
return true;
} catch (DateTimeParseException e) {
return false;
}
}
If input argument is "2011/12/12aaaaaaaaa", output is false;
If input argument is "2011/12/12", output is true
After it successfully parsed the entire pattern string SimpleDateFormat stops evaluating the data it was given to parse.
Take a look on the method documentation which says: ParseException if the beginning of the specified string cannot be parsed.
Method source code with javadoc:
/**
* Parses text from the beginning of the given string to produce a date.
* The method may not use the entire text of the given string.
* <p>
* See the {#link #parse(String, ParsePosition)} method for more information
* on date parsing.
*
* #param source A <code>String</code> whose beginning should be parsed.
* #return A <code>Date</code> parsed from the string.
* #exception ParseException if the beginning of the specified string
* cannot be parsed.
*/
public Date parse(String source) throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}
You can use the ParsePosition class or the sdf.setLenient(false) function
Docs:
http://docs.oracle.com/javase/7/docs/api/java/text/ParsePosition.html
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)
Simply setting sdf.setLenient(false) will do the trick..

How to parse ambiguous String into Date?

I'm trying to figure out a "simple" way of parsing a String into a Date Object.
The String can be either yyyyMMdd, yyyyMMddHHmm or yyyyMMddHHmmSS.
Currently, I'm looking at the length of the String, and creating a DateParser depending on the length. Is there a more elegant way of doing this?
Or you can pad your string with zeros:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS") {
#Override
public Date parse(String s) throws ParseException {
return super.parse((s + "000000").substring(0, 14));
}
};
System.out.println(sdf.format(sdf.parse("20110711182405")));
System.out.println(sdf.format(sdf.parse("201107111824")));
System.out.println(sdf.format(sdf.parse("20110711")));
I would do as you are, looking at the length of the string, and creating an appropriate SimpleDateFormat instance.
SimpleDateFormat getFormatFor( String dateString ){
if ( dateString.length() == 8 ) return new SimpleDateFormat("yyyyMMdd");
if ( dateString.length() == 14 ) return new SimpleDateFormat("yyyyMMddHHmmss");
// you got a bad input...
}
NB these are not thread-safe, so you should create a new one each time.
I would use a SimpleDateFormat class, and populate the format pattern based on the length of the string. That'll work fine unless you one day have strings of the same length.
Using the examples from your question:
Formatting 11th July 2011:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date parsedDate = dateFormat.parse("20110711");
Formatting 11th July 2011 1340hrs:
dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
parsedDate = dateFormat.parse("201107111340");
Formatting 11th July 2011 1340hrs 10 seconds:
(NB. small s for seconds, capital S is for Milliseconds!)
dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
parsedDate = dateFormat.parse("20110711134010");
See the hyperlink for the full list of format pattern letters.
You could still used "specialized" parsers (as you suggested) and chain them:
For instance, you can still have a DateHourMinSecParser (for yyyyMMddHHmmSS), a DateHourMinParser (for yyyyMMddHHmm) and a DateParser (for yyyyMMdd) all of them implementing the same interface:
public interface GenericDateParser {
Date parseDate(String input) throws IllegalArgumentException;
}
e.g.
public class DateHourMinSecParser implements GenericDateParser {
...
public Date parseDate(String input) throws IllegalArgumentException {
...
}
}
but each one of these classes would actually take a parameter another GenericDateParser -- the idea being that each parser would try first to parse the date itself, if the parsing (or some internal checks -- e.g. string length) fails it would then pass it to the next parser in chain until either there are no more parsers in the chain (in which case it would throw an exception, or one of the members in the chain would return a value):
public class DateHourMinSecParser implements GenericDateParser {
private GenericDateParser chained;
public DateHourMinSecParser(GenericDateParser chained) {
this.chained = chained;
}
public Date parseDate(String input) throws IllegalArgumentException {
if( !internalChecks() ) { //chain it up
if( chained == null ) throw new IllegalArgumentException( "Don't know how to parse " + input);
}
//internal checks passed so try to parse it and return a Date or throw exception
...
}
}
and you would initialize them:
GenericDateParser p = new DateHourMinSecParser( new DateHourMinParser(new DateParser(null)) );
and then just use the top level one:
Date d = p.parse( '20110126' );
You can use a DateFormatter to parse the Date from the string.
import java.util.*;
import java.text.*;
public class StringToDate
{
public static void main(String[] args)
{
try
{
String str_date="11-June-07";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date)formatter.parse(str_date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
}
}
You can change the pattern however you like to reflect your needs.

Categories