SimpleDateFormat returns invalid date - java

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

Related

How to Set Date to JdateChooser in java?

enter image description here
I used java Jcalender_1.4.jar
I have date like this,
String date = "13 Oct 2016";
i want this date set to JdateChooser text box,
by using this command JdateChooser.setDate();
how to covert string in to date format ?
You can do it using this easily by SimpleDateFormat command
String date = "13 Oct 2016";
java.util.Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
JdateChooser.setDate(date2);
and also you can use any date format.
Calendar ca = new GregorianCalendar();
String day = ca.get(Calendar.DAY_OF_MONTH) + "";
String month = ca.get(Calendar.MONTH) + 1 + "";
String year = ca.get(Calendar.YEAR) + "";
if (day.length() == 1) {
day = "0" + day;
}
if (month.length() == 1) {
month = "0" + month;
}
String dd = year + "-" + month + "-" + day;
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dd);
jDateChooser1.setDate(date);
try this set date form computer date
The following was first written as an answer to this duplicate question. I thought it would be better to have it here so we have all the answers in one place.
The following should work overall, only the details depend on the format of the dates in the JTable (from the other question). I have assumed that from the JTable you get a string like 03/07/2018 (I am told that this format would be commonplace in Portugal). In this case the following formatter will be fine for parsing it. If the string is in a different format, the formatter will have to be different too.
DateTimeFormatter dtfFormatador = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("pt-PT"));
LocalDate data = LocalDate.parse(getData, dtfFormatador);
Instant instante = data.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date dateAntiquado = Date.from(instante);
jdcSeletorDeDatas.setDate(dateAntiquado);
Unfortunately JDateChooser.setDate() requires an old-fashoined Date object, while we’d have preferred to avoid that outdated class. I am using a DateTimeFormatter for parsing the string from the JTable into a LocalDate and converting it to Date. LocalDate is the class from java.time, the modern Java date and time API, that we should use for a date without time of day.
Edit: harsha, your string was
String date = "13 Oct 2016";
To parse a string in this format, use the following formatter:
DateTimeFormatter dateFormatter= DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
Otherwise use the code above, where jdcSeletorDeDatas is the JDateChooser.
Link: Oracle tutorial: Date Time explaining how to use java.time.
try {
String date = "13 Oct 2016";
Date date2 = new SimpleDateFormat("dd MMM yyyy").parse(date);
jDateChooser2.setDate(date2);
} catch (Exception e) {
System.out.println(e);
}
Right Click on JDateChooser
Go to Properties
Change dateFormatString as "dd MMM yyyy"
Try to cast the value to the Date type. This Worked for me:
int SelectRow = jTable1.getSelectedRow();
jDateChooser1.setDate((Date) jTable1.getModel().getValueAt(SelectRow, 2));

Java date displays previous day , month and totally different year

I am trying to display Date based on timezone.
If I change my system time zone to US pacific time zone, today's date is displayed correctly. If I want to display 2000-01-01 output shows as 12/31/1969.
Can you please let me know if I have to make any change in system settings or java settings?.
Below is the example code:
package timezoneexample;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneExample {
public static void main(String args[]) {
DateFormat dateFormat = null;
String datePattern = null;
char dateSeperator = '/';
try {
datePattern = "MM/dd/yyyy";
if (datePattern.length() <= 0)
throw new java.util.MissingResourceException(
"Didn't find date format", "", "");
boolean hasSeperatorAlready = false;
for (int i = 0; i < datePattern.length(); i++)
if (!Character.isLetter(datePattern.charAt(i)))
if (hasSeperatorAlready)
throw new java.util.MissingResourceException(
"Unvalid date format", "", "");
else
dateSeperator = datePattern.charAt(i);
} catch (java.util.MissingResourceException mre) {
System.out.println(mre);
}
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
if (datePattern.length() > 0
&& dateFormat instanceof java.text.SimpleDateFormat) {
java.text.SimpleDateFormat sdf = (java.text.SimpleDateFormat) dateFormat;
sdf.applyPattern(datePattern);
}
dateFormat.setTimeZone(java.util.TimeZone.getDefault());
// enter DOB
Date dob = new Date(2000 - 01 - 01);
Date today = new Date();
String timeZone = System.getProperties().getProperty("user.timezone");
TimeZone tZone = TimeZone.getTimeZone(timeZone);
System.out.println("Timezone : " + tZone);
dateFormat.setTimeZone(tZone);
System.out.println("Date Of Birth : " + dateFormat.format(dob));
System.out.println("Date in Displayed as per Timezone : "
+ dateFormat.format(today));
}
}
Output:
Timezone : sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
Date Of Birth : 12/31/1969
Date in Displayed as per Timezone : 01/07/2015
Your error is here:
Date dob = new Date(2000 - 01 - 01);
This will be interpreted as:
Date dob = new Date(1998);
This will invoke the Date(long date) constructor, resulting in a date near 1970/01/01.
What you most probably want is:
Date dob = new Date(2000, 1, 1);
new Date(...) requires a long value, expressing the number of milliseconds since 1/1/1970. You're specifying 2000 - 1 - 1. This is NOT "year 2000, month 1 and day 1", it is a numeric expression equal to 1998 milliseconds.
To create a date based on year/month/day, use a Calendar:
Calendar c = Calendar.getInstance();
c.set(y, m-1 /* 0-based */, d); // e.g. c.set(2000, 0, 1);
return c.getTime();

Using SimpleDateFormat in 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.

Dates comparison in Java

I'm trying to compare two dates with the current date. It seems not to work when I try to know if a date is the same as the current date. Here's what I do in my code :
//BeginDate is set earlier
Date myDate= new SimpleDateFormat("dd/MM/yyyy").parse(BeginDate);
Date now = new Date();
System.out.println("Now : " + now);
System.out.println("myDate : " + myDate);
System.out.println("equals : " + myDate.equals(now));
System.out.println(myDate.compareTo(now));
And I get this in the console :
Now : Thu Dec 29 00:28:45 CET 2011
myDate : Thu Dec 29 00:00:00 CET 2011
equals : false
-1
The first comparison should return true and the second "0" right ? Or am I missing something ?
Comparing dates with either equals() or compareTo() compares the times (hours, minutes, seconds, millis) as well as the dates. Your test is failing because myDate is midnight today, whereas now is a little later than that.
Your comparison is failing because you need to format now so that both dates have the same format and thus may be compared.
Or, if you prefer, you can convert dates into strings and perform the comparison:
String beginDate = "28/12/2011";
Calendar now = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String nowStr = df.format(new Date());
System.out.println("equals : " + beginDate.equals(nowStr));
Are you specifying the milliseconds when creating the dates? If you are, don't. So when creating the dates earlier, only specify the Day, Hour etc, not seconds/milliseconds.
And, change the SimpleDateFormat respectively. That "should" work.
Date object in Java is nothing but a number that represents milliseconds since January 1, 1970, 00:00:00 GMT. It doesn't have any attribute called day, date, month, year etc. That's because date, month, year varies based on the type of calendar and timezone. These attributes belong to Calendar instance.
So, if you have 2 Date objects and you want to compare day of month, month and year then you should create corresponding Calendar instance and compare them separately.
// Parse begin date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = dateFormat.parse(beginDateAsString);
// Create calendar instances
Calendar beginDateCalendar = Calendar.getInstance();
beginDateCalendar.setTime(beginDate);
Calendar todayCalendar = Calendar.getInstance();
// Check Equals
boolean dayEquals = todayCalendar.get(Calendar.DAY_OF_MONTH) == beginDateCalendar
.get(Calendar.DAY_OF_MONTH);
boolean monthEquals = todayCalendar.get(Calendar.MONTH) == beginDateCalendar
.get(Calendar.MONTH);
boolean yearEquals = todayCalendar.get(Calendar.YEAR) == beginDateCalendar
.get(Calendar.YEAR);
// Print Equals
System.out.println(dayEquals && monthEquals && yearEquals);
Above code is cumbersome for the current problem but explains how date operations must be done in JAVA.
If you just want to solve the equals problem you have mentioned then the code below will suffice:
String todayAsString = (new SimpleDateFormat("dd/MM/yyyy")).format(new Date());
System.out.println(beginDateAsString.equals(todayAsString));
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR) - 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, Date (only) comparison can be achieved by checking if the number of days since 1900 of the 2 dates are equal.
NOTE: The above method should have code added to check if the dates are outside the valid range (1/1/1900 - 31/12/2099) and throw an IllegalArgumentException.
And don't ask me where this calculation came from because we've used it since the early '90s.

Date function in java

I have two dates
1) from_date: eg. 01/01/2010 (1st January 2010)
2) present_date: eg. 05/06/2011 (5th June 2011)
I want the third date as:
3) req_date: eg. 01/01/2011(1st January 2011)
Year should come from "present_date" and day and month should come from "from_date".
The dates which I mentioned are hardCoded.
In my code, I run a query to get these 2 dates.
Look into the Calendar class
http://www.java-examples.com/add-or-substract-days-current-date-using-java-calendar
Something like // Untested
Calendar cal=Calendar.getInstance();
cal.setTime(from_date);
Calendar cal2=Calendar.getInstance();
cal2.setTime(present_date);
Calendar cal3=Calendar.getInstance();
cal3.set(cal2.get(CALENDAR.YEAR),cal1.get(CALENDAR.MONTH),cal1.get(CALENDAR.DATE));
Date reg_date = cal3.getTime();
You can set individual fields of dates:
Date req_date = from_date;
req_date.setYear (present_date.getYear());
Or, if you're using Calendar (Date is deprecated):
Calendar req_date = from_date;
req_date.set (YEAR, present_date.get(YEAR));
If they're strings, you can just use substringing to get what you want:
String req_date = from_date.substring(0,6) + present_date.substring(6);
(assuming XX/XX/YYYY as seems to be the case).
Not sure if I understand you correctly but this example should get you started:
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
this way you can convert date Strings to java.util.Date object, then you can construct the third date by using Date/Calendar methods
from_date: for EX. 01/01/2010 (1 st January 2010)
present_date :for EX. 05/06/2011(5th june 2011)
String s1[]=from_date.split("/");
String s2[]=present_date.split("/");
String newDate=s1[0]+"/"+s1[1]+"/"+s2[2];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}

Categories

Resources