My code:
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(sdf.format(date));
System.out.println(sdf.format(sdf.parse(sdf.format(date))));
and this output I get:
2013-02-08 15:48:37
2013-12-30 15:48:37
expected output:
2013-02-08 15:48:37
2013-02-08 15:48:37
look at the day and month of date
The problem comes from the method "parse"
==> "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. "
The method may not use the entire text of the given string.
I've run your code and got the following :
System.out.println(sdf.format(date));
System.out.println(sdf.parse(sdf.format(date)));
System.out.println(sdf.format(sdf.parse(sdf.format(date))));
Result :
2013-02-08 14:54:39
Mon Dec 31 14:54:39 CET 2012
2013-12-31 14:54:39
As you can see the parse function converts the time correctly, but not the date itself. I think it is not intended to be used that way and therefore produces a weird result.
However, this is the first time I notice this, so I will not be able to give more details :)
To keep things simple, lets use a basic test case:
String date = "2013-02-08 15:48:37";
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
System.out.println(sdf.parse(date));
// Output: Mon Dec 31 15:48:37 CET 2012
According to the SimpleDateFormat Javadoc, the format specifier Y is used to denote the "Week year". The correct format specifier for the "Year" is y - with this, we get the correct output:
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.parse(date));
// Output: Fri Feb 08 15:48:37 CET 2013
Assuming that log is some kind of a logger, its standard practice for them to print out the time date and log level for every line. It makes it easier to debug from the log if need be,
I cannot reproduce this:
public static void main(String[] args) {
// TODO code application logic here
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
Logger log = Logger.getLogger("InfoLogging");
log.info(sdf.format(date));
try {
log.info(sdf.format(sdf.parse(sdf.format(date))));
} catch (Exception e) {
e.printStackTrace();
}
}
Gives output:
Feb 8, 2013 2:57:09 PM javaapplication2.JavaApplication2 main
INFO: 2013-02-08 14:57:08
Feb 8, 2013 2:57:09 PM javaapplication2.JavaApplication2 main
INFO: 2013-02-08 14:57:08
Which Logger are you using?
Related
This question already has answers here:
Parsing SimpleDateFormat
(2 answers)
Closed 6 years ago.
public static void main(String[] args) {
Date now = new Date();
String dateString = now.toString();
System.out.println(" 1. " + dateString);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
Date parsed = format.parse(dateString);
System.out.println(" 2. " + parsed.toString());
} catch (ParseException pe) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}
System.out.println(" 3. " + format.format(now));
}
print in console:
1. Thu Feb 23 17:14:51 CET 2017
ERROR: Cannot parse "Thu Feb 23 17:14:51 CET 2017"
3. jeu. févr. 23 05:14:51 CET 2017
instead of:
1. Thu Feb 23 17:14:51 CET 2017
2. Thu Feb 23 17:14:51 CET 2017
3. jeu. févr. 23 05:14:51 CET 2017
It looks like your default Locale is FRENCH, and since SimpleDateFormat uses it if you don't specify another one, you can't successfully parse english abreviations like Thu or Feb.
However, you can specify the use of the ENGLISH Locale like this:
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
You have run into one of the many diseases of the now out-dated Date class in Java.
The sound and easy fix is to change over to the Java 8 date and time classes. The new class that best corresponds to Date is Instant. With this class your code becomes:
Instant now = Instant.now();
String dateString = now.toString();
System.out.println(" 1. " + dateString);
try {
Instant parsed = Instant.parse(dateString);
System.out.println(" 2. " + parsed.toString());
} catch (DateTimeParseException e) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}
I have left out 3. from your example. Of course it is possible to format the Instant in about any way you could dream of, but if we just want the same output as from the toString method I don’t find it worth it for now. Rather I would like to show that for this case you don’t need a format at all. The code prints:
1. 2017-02-23T17:07:19.775Z
2. 2017-02-23T17:07:19.775Z
You notice that it prints the time in UTC. If you want your local time zone instead, just use ZonedDateTime instead of Instant. The rest of the code is exactly the same, but now output on my computer is:
1. 2017-02-23T18:07:19.852+01:00[Europe/Berlin]
2. 2017-02-23T18:07:19.852+01:00[Europe/Berlin]
Of course it is possible to generate an error like the one you get from disagreeing locales also with the new classes. As far as I can see, you would have to explicitly specify disagreeing locales. So you don’t do it easily.
I'm having huge difficulties with simple date format. First of all, I know not all tutorials on all sites are actually good, but the fact that all non trivial formats (not dd/MM/yyyy) gave a parse exception (plus my own tests don't work as expected) is rather frustrating to me.
This is the site in question: http://www.mkyong.com/java/how-to-convert-string-to-date-java/
And I don't understand why something as simple as:
private static void unexpectedFailure() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
Throws a parse exception.
Also besides that, I'm trying to parse my own dates. This code gives strange results (unexpected I would say):
public static void doSomething(List<String> list) {
Iterator<String> iter = list.iterator();
String[] line = iter.next().split(" ");
System.out.println(Arrays.toString(line));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
format.setLenient(true);
try {
System.out.println(line[0]+" "+line[1]);
System.out.println(format.parse(line[0]+" "+line[1]));
} catch (ParseException e) {
System.out.println("In theory this should not get caught.");
}
}
Prints out this:
[06/08/2015, 13:51:29:849, DEBUG, etc...]
06/08/2015 13:51:29:849
Thu Aug 06 13:51:29 EEST 2015
Thu Aug 06 13:51:29 EEST 2015 WHAT? WHY?
EDIT I'll try and explain. In my last code snippet I'm just trying to determine if the string is a date, and it passes "the test". However when I'm printing it out the format is simply bizzare. I'm starting to think that is because I'm printing a date. How can I even print a DateFormat? What I was expecting was dd/MM/yyyy hh:mm:ss not ddd MMM 06? hh:mm:ss G YYYY
And I don't understand why something as simple as:
(code snipped)
Throws a parse exception.
My guess is that it's tripping up over Jun which may not be a valid month abbreviation in your system default locale. I suggest you specify the locale in your SimpleDateFormat constructor:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Then you're dealing with a locale which definitely has Jun as a month abbreviation.
That said, where possible I'd suggest using numeric formats where possibly, ideally ones following ISO-8601, e.g.
yyyy-MM-dd'T'HH:mm:ss
However when I'm printing it out the format is simply bizzare.
No it's not. You're effectively using
Date date = format.parse(line[0]+" "+line[1]);
System.out.println(date);
So that's calling Date.toString(), documented as:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So that's working as expected. However, you want to format the date using your SimpleDateFormat - so you need to call format:
System.out.println(format.format(date));
Of course that just checks that it can round-trip, basically.
As a side note, I suspect you want HH (24-hour clock) instead of hh (12-hour clock) in your format string.
This question already has answers here:
Date Format JAVA
(5 answers)
Closed 9 years ago.
I have a date in the following format
//input date
Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)
//output date format
I want to change this to "dd-mm-yyyy, hh:mm:ss".
I get the input date format from db. I have to change that into output date format which i will be showing it in a grid.
I tried the following code.
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
try
{
Date date = outputDate.parse(facade.getDate.toString()); **//getting exception here**
outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
Date date1 = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").parse(outputDate
.format(date));
facade.setDate(date1);
}catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting
java.text.ParseException: Unparseable date: "2013-06-06 00:00:00.0".
Any help..
"2013-06-06 00:00:00.0" does not match "dd-mm-yyyy, hh:mm:ss" your format should be "dd-MM-yyyy hh:mm:ss" instead
But, looking at your code I'm guessing facade.getDate is actually a java.sql.Timestamp which inherits from java.util.Date so you can directly pass it to the format like so
new SimpleDateFormat("dd-MM-yyyy, hh:mm:ss").format(facade.getDate)
Here's some code which works for me:
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
String input = "Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)";
DateFormat inputFormat = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'z",
Locale.ENGLISH);
Date date = inputFormat.parse(input);
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",
Locale.ENGLISH);
outputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String output = outputFormat.format(date);
System.out.println(output);
}
}
Things to consider:
You need to work out your output time zone. Currently I've got it set to UTC, but that may not be what you want.
You really need to take a step back and think things through. You've clearly got two different formats - you're trying to convert from one to the other. So creating three different SimpleDateFormat objects all with the same format is never going to work.
You need to read documentation carefully... in SimpleDateFormat, M means month and m means minute; h uses the 12-hour clock and H uses the 24-hour clock.
This is assuming you actually need to start with a string though. If getDate is already a Date or a Timestamp, you can ignore the first part - just use the output part of the above code. You should avoid unnecessary string conversions wherever possible.
Note that dd-MM-yyyy is a slightly unusual format - are you sure you don't actually want yyyy-MM-dd which is more common (and sortable)?
DateFormat outputDate = new SimpleDateFormat("yyyy-dd-mm hh:mm:ss");
try {
Date date = outputDate.parse("2013-06-06 00:00:00.0");
System.out.println(new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
works well, line 1 was incorrect. Your SimpleDateFormat.parse needs to be in the exact format of the input date. Then you want to output it in a different format so you make another one and set the format then call SimpleDateFormat.format(date) and I put a println on it.
Fault is here
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
pattern should be equals to Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time). not to your out put strings pattern.
#Test
public void test() throws ParseException {
SimpleDateFormat sdf_org = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
Date d = sdf_org.parse("Thu Jun 06 2013 00:00:00 GMT+0530");
SimpleDateFormat sdf_target = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSS");
System.out.println(sdf_target.format(d));
}
output console : 2013-30-06 03:30:00.000
I have the following code:
SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd HH:mm");
try {
Date date=format.parse("2012.9.11 02:00");
Log.i("date", date.toGMTString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("exception", e.getMessage());
}
But I've got the message: "10 Sep 2012 22:00:00 GMT", i.e. incorrect date. How can I fix it?
That IS the correct date. It is calculated based on your GMT offset.
To print it like this 11-Sep-2012 02:00:00 use date.toLocaleString() (deprecated method)
Or you can print the date using the Calendar class using:
SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd HH:mm");
Date date=format.parse("2012.09.11 02:00");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.11 02:00
You can see http://www.vogella.com/articles/JavaDateTimeAPI/article.html for more info
You're printing date.toGMTString() and so you get "10 Sep 2012 22:00:00 GMT" which isn't an incorrect string but the date in Greenwich Mean Time. Note that toGMTString is deprecated.
If you want to print your date in your format, you may do
Log.i("date", format.format(date));
If you don't want to get supplementary "0", use
format=new SimpleDateFormat("yyyy.M.d HH:mm");
The method toGMTString() is deprecated.
However, as for an explanation, you might be in different time zone, thus have a different locale.
Try replacing with date.toLocaleString() should output correctly, although also a deprecated method.
As Per JavaDoc, date.toGMTString() is a deprecated method.
Its not good practice to use deprecated methods.
Use date.toString() instead of date.toGMTString().
Or
format.format(date);
It is incorrect because you're using date.toGMTString()
Just try to output the variable date and you'll able to see the correct time!
I need to work with dates and I wasn't sure how to go about that in Java since I have never done it before.
I am pulling dates from the Excel file and they can be retrieved in the Data format which would represent the date.
Ex:
2/1/2010
5/12/2011
8/15/2011
9/1/2011
9/1/2011
All my codes are pretty irrelvent to the question, but I am setting up a getter/setter method:
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
So my question is this, in what way when I am pulling the data from Excel:
temp.setDate((row.getCell(3).getDateCellValue());
I can set the limit so it only retrieves data from x amount of months. 8, 12, et.. from the last month/year displayed in the file, instead of going back all the way to 2010? I can provide more details if needed.
Edit: This is what I have now:
import java.util.Date;
Date date;
date = row.getCell(3).getDateCellValue();
It shows: Tue June 01 00:00:00
I don't care about Tuesday or 00:00:00, I just have a whole list of data and I only want to show x amount of months.
Edit: I figured it out. :)
The question is pretty vague, but if you are using Excel I have found it very beneficial to save the file as a 'filename.csv'. This format very easy to work with, it is comma delimited going across and newlines going down. If you are periodically checking the month, it would be easy to ensure that you only go x months backwards.
First you need to parse the dates accordingly using the SimpleDateFormat class. The result is a date object.
SimpleDateFormat df = new SimpleDateFormat( "M/d/yyyy" );
Date date = df.parse(row.getCell(3).getDateCellValue());
Then:
Calendar cal = Calendar.getInstance();
will return you an object ob type Calendar, where you can set the date by
cal.setTime(date);
Finally your loop reading the Excel file can determine according to the calendar object, if the date should be included / further processed by using:
int month = cal.get(Calendar.MONTH); // e.g. 11 for Nov
int year = cal.get(Calendar.YEAR); // e.g. 2011
You have to work with DateFormat.class fo parse the cell, or use a Calendar to put Day Month Year
EDIT
You can also use Calendar.class
final String[] tabDate = {"2/1/2010", "5/12/2011", "8/15/2011",
"9/1/2011", "9/1/2011"};
// Extract field's value
final Calendar c = Calendar.getInstance();
// Parse the list of stringDate
for (final String string : tabDate) {
System.out.println("Input string: " + string);
final String[] shortDate = string.split("/");
// Build Calendar
c.set(Integer.valueOf(shortDate[2]), Integer.valueOf(shortDate[0]),
Integer.valueOf(shortDate[1]));
// Extract date as you like
System.out.format("%25s : %d/%d/%d\t%s\n\n", c.getTime(),
c.get(Calendar.MONTH), c.get(Calendar.DATE),
c.get(Calendar.YEAR), c.getTimeInMillis());
}
Console :
Input string: 2/1/2010
Mon Mar 01 09:09:48 CET 2010 : 2/1/2010 1267430988109
Input string: 5/12/2011
Sun Jun 12 09:09:48 CEST 2011 : 5/12/2011 1307862588109
Input string: 8/15/2011
Thu Sep 15 09:09:48 CEST 2011 : 8/15/2011 1316070588109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109