SimpleDateFormat doesn't work - java

I'm trying to do something with a SimpleDateFormat, but after I read the Javadoc, I only got more confused. I want two methods, one for the timezone and one for the current time and date. My format should look like this:
Time Zone: GMT +01:00
Time and Date: Wednesday 17/04/2013, 20:38:34
I took code from the internet once for time. That worked fine:
private String getFormattedTime() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(cal.getTime());
}
This will output: 20:41:34
Now for my other format, I tried something like this (I wasn't completely done yet):
private static String getFormattedDate() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEEEEEEE DD/MM/yyyy, HH:mm:ss");
return sdf.format(cal);
}
private static String getTimeZone() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("z");
return sdf.format(cal.getTimeZone());
}
If you'd run this code, you get an IllegalArgumentException at the first return line.
It seems like the Javadocs don't give any example on how to use this.

SimpleDateFormat acts on Dates, not Calendars. To convert, use .getTime(), so your code should read:
private static String getFormattedDate() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEEEEEEE dd:MM:yyyy, HH:mm:ss");
return sdf.format(cal.getTime());
}
private static String getTimeZone() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("z");
return sdf.format(cal.getTime());
}
However, using joda is probably a better way to go for reasons I could write a PhD thesis on.

Related

How to Convert string to xml gregorian calendar date java

I am trying to convert String to gregoriancalendar date, it unable to convert. because, the string has different format. like '2015-05-22T16:28:40.317-04:00'. I have seen some of the other examples, but they are not in this time format.
I am using something like below:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz").parse(sampleDate));
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);
I even tried like this too:
gregory.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(sampleDate));
If you check SimpleDateFormat doc, you will see that there's no T in the format pattern. In order to escape non-pattern characters, wrap them around single quotes ' as shown in this example (taken from the docs):
"hh 'o''clock' a, zzzz" -> 12 o'clock PM, Pacific Daylight Time
I think the proper format should be this:
String format = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
// ^-^-----check these
// don't pay attention to the smiley generated above, they're arrows ;)
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new SimpleDateFormat(format).parse(sampleDate));
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);
This works as well
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317-04:00");
GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz");
//dateFormat.setTimeZone(TimeZone.getTimeZone());
Date inputDate = dateFormat.parse(inputDatetime);
GregorianCalendar c = new GregorianCalendar();
c.setTime(inputDate);
XMLGregorianCalendar outputDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
return outputDate;
} catch (ParseException | DatatypeConfigurationException e) {
log.error("exception: {}", e.getMessage());
return null;
}

Changing the date

Basically, I've got a little program that uses date.
Date current = new Date();
current.setDate(current.getDay() + time1);
When I do this it adds to the day, but say time1 = 30 then the month doesn't change when I print the date out. I hope this makes sense I'm kinda new to this.
Use a Calendar to perform date arithmetic and a DateFormat to display the result. Something like,
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 30);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(cal.getTime()));
Use this method
public static Date addDaystoGivenDate(Integer days, Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}

Difference between date in miliseconds and its Calendar representation

I have two functions which convert a date String to a date in milliseconds:
public static long convertYYYYMMDDtoLong(String date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d = f.parse(date);
long milliseconds = d.getTime();
return milliseconds;
}
If I run this function I get the following result:
long timeStamp = convertYYYYMMDDtoLong("2014-02-17");
System.out.println(timeStamp);
It prints:
1389909720000
Now, if I run the following code:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeStamp);
System.out.println(cal.getTime());
It prints out:
Fri Jan 17 00:02:00 IST 2014
Why is my date shifted by one month? What is wrong?
P.S: My problem is that I need to map the date, represented as long, to another third party API which accepts Calendar format only.
You're using mm, which is minutes, not months. You want yyyy-MM-dd as your format string.
It's not clear why you're not returning a Calendar directly from your method, mind you:
private static final TimeZone UTC = TimeZone.getTimeZone("Etc/UTC")
public static Calendar convertYYYYMMDDtoCalendar(String text) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
format.setTimeZone(UTC);
Calendar calendar = new GregorianCalendar(UTC);
calendar.setDate(format.parse(text));
return calendar;
}
(That's assuming you want a time zone of UTC... you'll need to decide that for yourself.)

Processing Java Strings and Dates

I need to process a list of Strings which may or may not be times. When I do receive a time, it will need to be converted from "HH:mm:ss" to number of milliseconds before processing:
final String unknownString = getPossibleTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
final Date date = dateFormat.parse(unknownString);
//date.getTime() is NOT what I want here, since date is set to Jan 1 1970
final Calendar time = GregorianCalendar.getInstance();
time.setTime(date);
final Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
final long millis = calendar.getTimeInMillis();
processString(String.valueOf(millis));
}
catch (ParseException e) {
processString(unknownString);
}
This code works, but I really dislike it. The exception handling is particularly ugly. Is there a better way to accomplish this without using a library like Joda-Time?
public static long getTimeInMilliseconds(String unknownString) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(Calendar.getInstance().getTime());
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeFormat.parse(dateString + " " + unknownString).getTime();
}
Handle the ParseException outside of this method however you'd like. I.e. ("No time information provided"... or "unknown time format"... etc.)
.getTime() returns the time in milliseconds. It's part of the java.util.Date API.
Why don't you first check if the input is actually of HH:mm:ss format. You can do this by trying match input to regex [0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9] first and if it matches then treat it as date otherwise call processString(unknownString);

Date showing is wrong

I use this method to generate my today date to write it to file.
public void DateFiledControl() {
Calendar currentTime = Calendar.getInstance();
SimpleDateFormat myFormat = new SimpleDateFormat("YYYY/MM/DD");
String strDate = myFormat.format(currentTime.getTime());
System.out.println(strDate);
}
But , my result is : 2013/03/63
Why?!
Because you should be using dd instead of DD, which the SimpleDateFormat documentation makes fairly clear.
Also, be aware that 'MM' is the month, but 'mm' is the minutes.
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
try
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy/MM/dd");

Categories

Resources