Using SimpleDateFormat in java - java

I am trying the following code,
Calendar signupDate = Calendar.getInstance();
signupDate.set(Calendar.YEAR, 2014);
signupDate.set(Calendar.MONTH, 01);
signupDate.set(Calendar.DAY_OF_MONTH, 01);
Date signupDateTime = signupDate.getTime();
new Object[]{signupDateTime};
Date date = (Date) params[0];
String format = (String) params[1];
try {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
String expDateStr = (String) sdf.format(date);
System.out.println("Expiration Date: "+expDateStr);
} catch (Throwable t) {
throw new RuntimeException("Could not execute DateToString function for Date:" + params[0] + " with Pattern:" + params[1], t);
}
This program prints: Expiration Date: 2014-02-32
While debugging, i reached in into java.text.DateFormat class in Java API into the following function,
public final String format(Date date)
{
return format(date, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
Runtime value of date parameter for format function is: Fri Feb 01 17:58:30 PST 2013
But this function returns: 2014-02-32
I am not sure how does formatting converts 01 to 32.
Any suggestion?
Thanks,
Vijay Bhore

Feb 1st is the 32nd day of the year. Your SimpleDateFormat is probably using DD instead of dd.

This is dangerous:
signupDate.set(Calendar.MONTH, 01);
Don't use magic numbers like this since you or the next coder to maintain this code might not know that months are 0 based, that this sets the month to February not January.
Better:
signupDate.set(Calendar.MONTH, Calendar.JANUARY);
or
signupDate.set(Calendar.MONTH, Calendar.FEBRUARY);
Whichever was desired.

Related

Add one day to given date in Java and return in specific date format [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 4 years ago.
I wish to add one day to a given date.If i pass 2018-08-05,the below method returns 2018-08-06 which is expected. But if the pass the last date of the month -2018-08-31,it returns 2018-08-01 instead of expected result 2018-09-01.
DateFormat format = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date date = null;
try {
date = format.parse("2018-08-31");
} catch (ParseException e) {
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE ,1);
return format.format(cal.getTime());
You're using the old calendar/date API. This API is quite bad (it does weird things and does not accurately model how dates actually work).
It has been replaced with the new java.time API. I strongly suggest you use that instead. If you're on java7 or below, you can use the 'JSR310-backport' library to your dependency list to use this API. (JSR310 is the name for this addition to java).
In java.time, you'd do:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2018-08-31", fmt);
System.out.println(fmt.format(date.plusDays(1)));
// yyyy-MM-dd so happens to be the default for LocalDate, so...
// we can make it a lot simpler:
date = LocalDate.parse("2018-08-31");
System.out.println(date.plusDays(1));
}
}
The bug is in the pattern of your SimpleDateFormat which you use for input and output. This dual-use masks the error:
public class Main {
public static void main(String[] args) throws Exception {
DateFormat format = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date date = format.parse("2018-08-31");
System.out.println("format: " + format.format(date) +", real: " + date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE ,1);
System.out.println("format: " + format.format(cal.getTime()) +", real: " + cal.getTime());
}
}
This gives you:
format: 2018-08-31, real: Wed Jan 31 00:08:00 CET 2018
format: 2018-08-01, real: Thu Feb 01 00:08:00 CET 2018
Using the right pattern yyyy-MM-dd produces the right answer:
format: 2018-08-31, real: Fri Aug 31 00:00:00 CEST 2018
format: 2018-09-01, real: Sat Sep 01 00:00:00 CEST 2018
Since the new and the old Java-Time API use the same patterns, simply adopting the new API will not help in this case.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = null;
try {
date = format.parse("2018-08-31");
} catch (ParseException e) {
}
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.setTimeInMillis(cal.getTimeInMillis() + 86400000); //86400000ms = 1 day
return format.format(cal.getTime());

java.text.ParseException: Unparseable date: "531772200000"

I need to convert the string 531772200000 to a Java Date object. The date is stored in a database.
When I am doing this, I am getting java.text.ParseException: Unparseable date: "531772200000".
My code:
String dateToBeConverted = String.valueOf(dbObject.get("customerDateOfBirth"));
String parseabledate = dateToBeConverted
.replace("/Date(","")
.replace(")/","")
.replace("+0530", "");
dbObject.put("_id", String.valueOf(dbObject.get("userInfoId")));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date;
date = formatter.parse(parseabledate);
This looks like a timestamp value, this will probably give you the date:
new Date(Long.parseLong("531772200000"));
which works out at Fri Nov 07 1986 18:30:00 GMT+0000
Here is one solution that will provide the date correctly formatted.
String d = "531772200000";
SimpleDateFormat newFormatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date date1 = new Date(Long.parseLong(d));
System.out.println(newFormatter.format(date1)); //Will print out as 07-Nov-1986
} catch (ParseException e) {
e.printStackTrace();
}
Another solution is to use Joda Time with a solution below.
String d = "531772200000";
DateTime newDate = new DateTime(Long.parseLong(d));
DateTimeFormatter dd = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime date = dd.parseDateTime(newDate.toString());
System.out.println(date.toString("dd-MMM-yyyy")); //Prints out as 07-Nov-1986
Personally I prefer to use the second solution (Joda Time) as it is much nicer and easier.
It is epoh time format.
Somebody already answered about that in https://stackoverflow.com/a/20732668/379779
and test your epoh time in this website http://www.epochconverter.com/

How to parse "dd-MM" date format to get current year?"

I have to parse "17-Jun" format date using Java.But the problem is when I try to parse "dd-MM" format using SimpleDateFormat it is returning as "Wed Jun 17 00:00:00 IST 1970".Is it possible to get current(2014) year instead of 1970.
My result:
17/JUNE/1970
Expected result:
17/JUNE/2014
Have a look at this..
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date date=new Date(c.getTimeInMillis());
SimpleDateFormat simpleDateformatter = new SimpleDateFormat("dd/mmm/yyyy");
String convertedDate = simpleDateformatter .format(date);
To get year you can just use
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR) will fetch you current year
Hope it helped... :)
Try this
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date d=new Date(c.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("dd- mmm");
String conDate = formatter.format(d);
Do like this
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
You'll have to write a utility method, there isn't anything in SimpleDateFormat that will interpret a non-existant year as the current year. Something like this:
public static Date parseDate(String dateString) throws ParseException {
//determine current year
Calendar today = Calendar.getInstance();
int currentYear = today.get(Calendar.YEAR);
//parse input
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date parsed = format.parse(dateString);
// set current year on parsed value
Calendar cal = Calendar.getInstance();
cal.setTime(parsed);
cal.set(Calendar.YEAR, currentYear);
return cal.getTime();
}
Try this:
SimpleDateFormat dfDate = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date d = null;
try {
d = dfDate.parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
System.out.println(""+d );
your problem will be solved.
java.time
In Java 8 you can do something like:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-MMM");
MonthDay md = MonthDay.parse("17-Jun", dtf);
LocalDate d = LocalDate.now().with(md);
System.out.println(d.getDayOfMonth());
System.out.println(d.getMonthValue());
System.out.println(d.getYear());
I guess the simplest way is to do this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MMM/dd");
Date date = new Date();
System.out.println("Time is: " + dateFormat.format(date) );
This gives you exactly what you want. also see
http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
Little late, but if you really don't want to use Calendar at all - as I gather from your comments to the correct answers above - (not recommended with the usage of deprecated methods, but still):
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date date = format.parse("17-JUN");
date.setYear(new Date().getYear());
System.out.println(date);
Output:
Tue Jun 17 00:00:00 IST 2014
All answers given here are more or less correct, but I notice that one detail aspect is still overlooked, namely if the combination of day and months fits to current year (february 29 problem). So I would suggest a strict parsing like following:
String ddMMM = "17-Jun";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
sdf.setLenient(false); // in order to check for "29-Feb"
TimeZone tz = TimeZone.getDefault(); // or change to your specific time zone
Date date =
sdf.parse(ddMMM + "-" + new GregorianCalendar(tz).get(Calendar.YEAR));
Try,
String s2 = "Wed Jun 17 00:00:00 1970";
SimpleDateFormat sdf1 = new SimpleDateFormat("E MMM dd hh:mm:ss yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MMM/yyyy");
try {
Date d1 = sdf1.parse(s2);
System.out.println(d1);
String s3 = sdf2.format(d1);
System.out.println("Before Changing :: "+s3);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
cal.add(Calendar.YEAR, 2014-1970);
d1 = cal.getTime();
String s4 = sdf2.format(d1);
System.out.println("After Changing :: "+s4);
} catch (ParseException e) {
e.printStackTrace();
}
Output
Before Changing :: 17/Jun/1970
After Changing :: 17/Jun/2014

SimpleDateFormat returns invalid date

I'm facing a really strange problem I haven't seen before. I have a date in milliseconds and want to display it as a readable date. This is my code:
if (validUntil == 0) {
return activity.getResources().getString(R.string.forever);
} else {
Date startDate = new Date(validFrom);
Date endDate = new Date(validUntil);
if (startDate.compareTo(endDate) < 0) {
String date = sdf.format(startDate) + " - " + sdf.format(endDate);
return date;
} else if (startDate.compareTo(endDate) == 0) {
return activity.getResources().getString(R.string.forever);
}
}
As you can see I just want to create a string which shows the time span. When I debug into my code, the date objects contain the right values while sdf.format(...) gives me an invalid date.
Example:
startdate in milliseconds: 1375017555000
startdate object contains: Sun Jul 28 15:19:15 CEST 2013
sdf.format(startDate) returns: 28.19.2013
I get a simillar result for the end date.
What am I doing wrong?
Probably it seems you have used mm to denote months , but it should be MM . Look at the documentation.
M month in year
m minute in hour
Try:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
You get minutes instead of months. Your pattern should be like this: "dd.MM.yyyy"
Looks like your date format string is incorrect. This works:
public static void dateFormat(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(format.format(new Date()));
}
Result:
2013-07-29

How to forcefully cast a string(generated by formating some date) into Date?

I have a string (Jan12) (generated by applying some operations on current date {20-jan-2012}) Now i want to convert back this string into Date format . Also the value should be same i.e the new Date object should have value jan12 and not (20-jan-2012) . Pls help . I have tried doing
java.sql.Date.valueOf("Jan12") [this throws IllegalArgumentException]
and also
new SimpleDateFormat("MMMyy").parse("Jan12") [By this Date gets converted to 20-jan-2012]
Output required : A Date Object having value Jan12 (12 is the year)
My Code : new java.text.SimpleDateFormat("MMMyy").format(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(s)) // It is a string which gives Jan12
Now i really want to convert Mycode into a Date object
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s1 = df.format(now);
System.out.println(s1); // 2012-01-20
java.sql.Date d111=java.sql.Date.valueOf(s1);
System.out.println(d111); // 2012-01-20
DateFormat df1 = new SimpleDateFormat("MMMyy");
String s2 = df1.format(d111);
System.out.println(s2); //Jan12
Now i want s2 to be converted in Date object
#Aditya,
If you use the Str2 which gives "Jan12", there is no date part in that string and therefore if you convert it to a date object, it will get "Jan" as month, 12 as year but it cant find "day" in that String.
if you use below code
try
{
Date d2 = df1.parse(s2); //here s2 is your string which gives "JAN12"
System.out.println(d2);
}
catch(ParseException pe)
{
System.out.println("parse exception..");
}
The output to the above code will be:
Sun Jan 01 00:00:00 IST 2012
notice here that day part is reset to the first day of the month
Therefore, it is not possible to get a complete date object as your original Date, the month and year are preserved, but the day part is lost.
What do you mean "gets converted"? How your Date is displayed is a separate issue. Look into formatting a Date.
So the 12 is day, not a year - you should parse it as such. Aslo, you'll need to tell it what year this is:
System.out.println(new SimpleDateFormat("yyyyMMMdd").parse("2012" + "Jan12"));
Output
Thu Jan 12 00:00:00 EST 2012
Use the SimpleDateFormat class properly, it will do exactly what you want
String str_date="12-Jan-2012";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse(str_date);
Note: the formatter.parse() method throws ParseException, catch it;
If 12 is a year
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMyy").parse("Jan12"));
calendar.set(Calendar.DATE, 1);
Date date = calendar.getTime(); // First Jan 2012
If 12 is a day
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMdd").parse("Jan12"));
calendar.set(Calendar.YEAR, 2012);
Date date = calendar.getTime(); // 12 Jan 2012
I understand that you want to format your Date object into a String representation.
You can use SimpleDateFormat for this, analog to your second example:
Date d = new Date(112, 0, 20); //don't construct a date like this in production code, use a Calendar instance instead
String formattedDate = new SimpleDateFormat("MMMyy").format(d); // -> "Jan12"
Note that your Date object represents a specific point in time, it will always have a day and a time associated with it.
If you want to compare Dates with the resolution of a month, you have to set day and time to neutral values:
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
Just extend Date and customize it to use your favourite parse & format methods.

Categories

Resources