Java SimpleDateFormat - java

I want to convert a date which may be several formats like yyyyMMdd,yyyy-MM-dd,yyyy/MM/dd to a standard for 'yyyy-MM-dd HH:mm:ss'. In the below code, I set the expected date format to 'yyyyMMdd' and then passed in '2014-02-21'. I was expecting a Parse Exception but some how this is returning '2013-12-02 00:00:00'.What am I missing here ?
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyyMMdd");
Date date = sdfSource.parse("2014-02-21");
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println( sdfDestination.format(date));

I would recommend adding sdfSource.setLenient(false); between the first two lines of that snippet.
What's happening here is that "-0" is being interpreted as the month, and "2" as the day. With leniency true (which is the default) this is acceptable - "-0" is interpreted as the month before the first month; that is "December of the previous year".

The lenient property is set to true by default. here
sdfSource.setLenient(false);

Related

how to get time stamp for the example: 2016-08-29T09:15:17Z?

I have tried to get the date format 2016-08-29T09:15:17Z but not able to get the trailing Z at the end.
I also checked the date time documentation at official website but could not find a similar pattern. So far the date format I have created is as follows:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
So far the code I have written is:
public static void main(String args[]) throws ParseException{
Date nDate=new Date();
//SimpleDateFormat format=new SimpleDateFormat("ddMMYYYYHHMMSS");
String date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(nDate);
System.out.println(date);
}
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use -
TimeZone timeZone = TimeZone.getTimeZone("UTC"); // optional
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
dateFormat.setTimeZone(timeZone); // optional
String date = dateFormat .format(new Date()); // date will have the required format
System.out.println(date);
Z is a constant value like T in your string, so you have to put single quotes arround it:
String date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(nDate);
If you use Z without single quotes DateFormat expect the timezone value
Oracle Documentation describe that z and Z both are use for time zone.
So if you don't want special meaning of Z then you need to write like :
yyyy-MM-dd'T'HH:mm:ss'Z'
I am adding another way to do it, using the new java.time API introduced from JDK 8 onwards.
LocalDateTime nDate=LocalDateTime.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendLiteral('Z')
.toFormatter();
String date = formatter.format(nDate);
System.out.println(date);

How to get particular parts of a DateTime object?

I have a DateTime object DT which stores current time. When I print DT, I want it to only print the time part, ie HH-MM-SS (H = hours, M = minutes, S = seconds) and ignore the date part.
How can I do this ? For that matter, is it even possible to create a date time object which will only contain HH-MM-SS and nothing related to date ? If that is true, then I can simply print it instead of extracting the HH-MM-SS part.
Thanks.
If you only want the time, you should use a LocalTime instead of a DateTime. You can use DateTime.toLocalTime() to get the time part of an existing DateTime.
If you actually want to keep the DateTime but only reveal the time part when formatting, you can create a DateTimeFormatter with a pattern which only includes the time parts, but I'd usually consider this a design smell.
You can use Java date formatter which is in java.util.Date package.
Like :
Date todaysDate = new java.util.Date();
1. // Formatting date into yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
2. // Formatting date into yyyy-MM-dd e.g 2008-10-10
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
3. // Formatting date into MM/dd/yyyy e.g 10/10/2008
formatter = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = formatter.format(todaysDate);
With Java you can do it like this
Date obj = new Date() ;
System.out.println(new SimpleDateFormat("hh:mm:ss").format(obj)) ;
but it could be an expensive call.
But jodatime gives LocalTime which you can try out.

String to Date not formatted correctly

I am trying to do a simple String to Date conversion in Java. I am skimming the date off some logs and need to convert it to a date to do some processing. A date coming through will look like this:
2012-09-07 19:53:33
In my code when I try to convert this into a Date object I get a completely different date. My code looks like this:
String taskStart = "2012-09-07 19:53:33";
String dateFormat = "yyyy-MM-dd hh:MM:ss";
SimpleDateFormat dateFormat=new SimpleDateFormat(format);
Date taskStartDate = dateFormat.parse(taskStart);
The output I get is this:
Sat May 07 19:00:27 PDT 2016
How can I just simply convert my original date to the correct format??
You've specified MM (month in year) twice. The m's for "minute" must be lowercase.
If you're taking 24-hour based times, you need to specify HH in order to capture hours that are specified in the range of 0-23, as opposed to hh which expects AM/PM hours (hours in the range of 1-12 with an AM/PM specifier as part of the time string)
Finally, your example code doesn't define the format variable that you're passing into the constructor for your SimpleDateFormat object. In fact, you're using the variable name dateFormat twice and not defining the format variable at all - at least not according to the code that you included in the question.
So, your proper format string, I believe, should be...
"yyyy-MM-dd HH:mm:ss"
...and the full, proper code example would be:
String taskStart = "2012-09-07 19:53:33";
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat dateFormat=new SimpleDateFormat(format);
Date taskStartDate = dateFormat.parse(taskStart);
According to the documentation for SimpleDateFormat you should use an upper case "H" for hours of the format 0-23. Also, minutes are represented by a lowercase "m".
String dateFormat = "yyyy-MM-dd HH:mm:ss";
I think you should convert again the date output to String format using date formatter.format function:
Date formatter=new SimpleDateFormatter("yy-MM-dd HH mm ss")
String s=formatter.format(taskStartDate)
Try changing your dateFormat definition to this:
String dateFormat = "yyyy-MM-dd HH:mm:ss";
Note that the in your time, HH should be capitalized for 0-23 and mm should be lowercase for minute.
"yyyy-MM-dd hh:MM:ss";
MM and mm are for Month and Minute respectively.....
So it should be...
"yyyy-MM-dd hh:mm:ss";

Java Date/Calendar oddness

I have a bit of (Java) that I where I am trying to simply subtract 7 days from the current date. It seemed to me like Calendar.add(..) should be the method to use (and what previous questions here seem to say), so that's what I tried:
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
System.out.println("ReportUtil.getDefaultReportStartDate cal: "+cal.toString() );
System.out.println("PRE ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
cal.add(Calendar.DATE, -7);
System.out.println("POST ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
That looks ok to me but you'll see from the output below the month field seems to go a bit... sideways! The day of the month/date seems to change correctly, but what is going on with the month?!
ReportUtil.getDefaultReportStartDate cal: java.util.GregorianCalendar[time=1330098699960,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GB-Eire",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=GB-Eire,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2012,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=55,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=51,SECOND=39,MILLISECOND=960,ZONE_OFFSET=0,DST_OFFSET=0]
PRE ReportUtil.getDefaultReportStartDate: 24-51-2012
POST ReportUtil.getDefaultReportStartDate: 17-51-2012
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
You get a strange month value because mm means minutes. Try:
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
You can consult the whole list of the format symbols here: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
mm is the format string for Minute. You want MM
Your result seems to be correct.
The month is "1" in both dates of your first log line, which means February.
The "-mm-" in your SimpleDateFormat means minute and not month, thus the odd month of "51"

Help Needed with Date Format in java

I have My Database data in this format
18-NOV-10
I have to pass the same format into java.util.Date like this
Date date = new java.util.Date(dateformater);
so that the result of java.util.Date is like this 18-NOV-10
Is this possible ??
I tried this way
String strDate = "12-NOV-07";
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MMM-yy");
Date date = sdfSource.parse(strDate);
System.out.println(date);
But i am getting the result as "Mon Nov 12 00:00:00 IST 2007 " which i want it only
12-NOV-07"
You can use java.text.DateFormat (actually SimpleDateFormat) to get you where you want to go, but maybe you shouldn't be storing the dates as strings in your database. It will do output and parsing.
SimpleDateFormat sdf =
new SimpleDateFormat("DD-MMM-YY");
Date parsed = sdf.parse(dateString);
See http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/
Once you get the Date, you can turn it into the format you want but it will be held in memory as a Date object. You can get it in the form you want using
String dateString = sdf.format(parsed);
As others have pointed out, you should probably store your dates as dates, not strings; nevertheless...
If you want to turn a Date back into a string in that format you can use the following:
DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date date = new Date();
String dateStr = formatter.format(date); // Gives "22-May-11"
If you need MAY instead of May, just use toUpperCase() on the resultant string.
DateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
Date d = sdf.parse("18-NOV-10");
Try System.out.println(sdfSource.format(date).toUpperCase()); instead. The Date object will always have a time component to it; there is no way to "disable" that feature. What you can do instead is to ignore it in your calculations and display. If all Date objects you use are set to the same time of the day, then you can safely ignore the effect of the time component in your comparisons. If you look carefully, the time component of your Date object is set to midnight.

Categories