Using Java libraries to parse date in particular form - java

I'm running an application which gives me CSV logs as output. For the date field, it gives it to me in the following form:
"09/25/2012 08:47:46.983"
I want to read in the output data into a Java program, translating the output given and storing it as a long in my program. Does the DateFormat class or other similar class in Java allow me to specify a string in the above form? (I can write my own code to parse the above line, but I didn't want to make bad assumptions about the form of the incoming string.)

public class TestTest {
public TestTest() {
String dateString = "09/25/2012 08:47:46.983";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss.SSS");
try {
Date date = dateFormat.parse(dateString);
System.out.println("Date is: " + date.getTime());
} catch (ParseException ex) {
Logger.getLogger(TestTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
TestTest test = new TestTest();
}
}

Related

SimpleDateFormat ParseException parsing minutes and seconds

I'm getting a parse exception when trying to run
SimpleDateFormat format = new SimpleDateFormat("mm:ss", Locale.US);
String str = "11:22";
Date time = format.parse(str);
I haven't the foggiest what I'm doing wrong.
Try doing this bud and tell me whether it works for you or not!
Date dateInput;
String str = "11:22";
DateFormat inputFormat = new SimpleDateFormat("mm:ss");
try {
dateInput = inputFormat.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
Do you need the output too of the parsed date? If yes then tell me will update the answer. And if you still get the exception then try to print the log cat output which you'll find in this section.
Go below and check this out and copy paste the logcat.
If the beginning of the specified string cannot be parsed method parse which is of DateFormat class will generate ParseException.
So, We need to catch that exception. One of the method is given below in java code
import java.text.*;
import java.util.*;
public class Prg
{
public static void main(String args[]) throws Exception
{
SimpleDateFormat format = new SimpleDateFormat("mm:ss", Locale.US);
String str = "11:22";
Date time = format.parse(str);
System.out.println(time.toString());
}
}

How to get only the Date Month and time from a String

I get the following string from Database "2015-03-17 15:27:38"
From this i want to show only
03-17 15:27 (Month - Date and Time with minutes and seconds)
I was trying the following way
import java.util.Random;
public class Test {
public static void main(String args[]) throws JSONException {
String created = "2015-03-17 15:27:38";
if (created != null && !created.isEmpty() && created.length() >= 19) {
created = created.substring(0, created.length() - 5);
}
System.out.println(created);
}
}
Could you please let me know how to do this ?
Use a SimpleDateFormat to parse the String value to a Date, then use another SimpleDateFormat to format the value the way you wan it
try {
String created = "2015-03-17 15:27:38";
SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = in.parse(created);
SimpleDateFormat out = new SimpleDateFormat("MM-dd HH:mm");
System.out.println(out.format(date));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication979.class.getName()).log(Level.SEVERE, null, ex);
}
Outputs 03-17 15:27
Unless you can guarantee that the format of your date will never change, you should not start to create your own string parsing code.
Java offers you various "built-in" APIs to deal with numbers and dates; for example https://docs.oracle.com/javase/tutorial/datetime/

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;
}
}

Simple time parsing of a String

In the below code i need to get a parse exception.but the program somehow converts it to a valid date.
But if i give dthours as "07:0567" it is giving parse error.So how to keep the exact format shown.
Can anyone tell me what to do to throw an error if the date string deviates from the given format ("HH:MM:SS") even by a single character.
public static void main(String[] args) {
String dthours="07:4856:35563333";
SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS");
try
{
Date d = df.parse(dthours);
System.out.println("d "+d);
}
catch (ParseException e)
{
System.out.println("parseError");
}
Set the df.setLenient() to false so that the SimpleDateFormat will throw parse exception in such cases.
public static void main(String[] args)
{
String dthours = "07:4856:35563333";
SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS");
df.setLenient(false);
try
{
Date d = df.parse(dthours);
System.out.println("d = " + d);
}
catch (ParseException e)
{
System.out.println("parseError");
}
}
The above snippet would print "parseError" for that input.

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