Java SimpleDateFormat not accepting ##/## - java

Below, I've got the code I'm trying to use. It always hits the catch, returning a null. Both month and day are integers, and they've already been checked to ensure they fall within existing dates on existing days. Regardless, I'm testing with "05" for the month and "02" for the day. Does an input of ##/## not work, for some reason?
public static Date getAlphabetDate()
{
try
{
String tempDate = month + "/" + day;
Date alphabetDate = new SimpleDateFormat("MMMM d").parse(tempDate);
return alphabetDate;
}
catch(Exception e)
{
return null;
}
}
EDIT: I'm trying to format this output so it looks like "May 02". When I look at the documentation, I see a huge section of the page is dedicated to formatting output. Why isn't mine formatting like that?

If your input is 02/05, you should use the corresponding date format:
public static Date getAlphabetDate()
{
try
{
String tempDate = month + "/" + day;
Date alphabetDate = new SimpleDateFormat("MM/dd").parse(tempDate);
return alphabetDate;
}
catch(Exception e)
{
return null;
}
}

you are parsing the string in the simpledataformat the wrongway..
try this:
String tempDate = month + "/" + day;
Date alphabetDate = new SimpleDateFormat("MM/d").parse(tempDate);

Your input doesn't match your format pattern...
Your input is in the form of MM/dd but you pattern is in the format of MMMM d, you will need to make one of these match
Try using
String tempDate = month + " " + day;
Date alphabetDate = new SimpleDateFormat("MM d").parse(tempDate);
Instead, for example...

Related

Android Time UTC

I am working on an Android app that frequently travels from Time Zone to TZ. I am getting various errors with times and TZs. The latest error is, when I load the flat file with times (see below), everything looks good. When I save the app environment (aka all variables/objects to sharedprefs), stop and then restart the app the time displayed is no longer local but UTC.
I began developing the app just using the default/local TZ. However, this became very complicated with DST and various TZs. Therefore my current approach is to store time in the app in UTC, and calculate differences between UTC times as needed. Then convert the UTC-stored time to the local TZ on-demand for user interaction.
I recognize there are many posts related to android time. I think I have read most if not all on java.util.date and Joda. However, I am still stuck. So, here goes...
I have 3 sources of time for the app. 1) I read in UTC Strings from a flat file 2) I get milliseconds since the Epoch for system time stamp (in UTC). 3) I get UTC in a string via a rest API. The app does numerous calculations between the 3 categories such as time difference, add time, etc. Below I will post my code for each of these
1 - Convert string UTCs that come from a file
public static Date string2date(String strformat, String strdate){
Date tdate = timestamp();
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat formatter = new SimpleDateFormat(strformat);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateInString = strdate;
try {
tdate = formatter.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
return tdate;
}
2 - Get milliseconds since Epoch
public static Date timestamp() {
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
//Date currentTime = localCalendar.getTime();
Date currentTime = GetUTCdatetimeAsDate();
return currentTime;
public static Date GetUTCdatetimeAsDate()
{
//note: doesn't check for null
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(longdt);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(longdt);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}
3 - Get UTC in a string via a rest API (Format is "2017-02-10T01:09:00Z")
try {
Calendar tempCal = ISO8601.toCalendar(dateLocal);
Log.e (" fbu "," fsutc " + tempCal.getTime() );
ISODepDate = tempCal.getTime();
tempCal = ISO8601.toCalendar(dateLocal2);
ISOArrDate = tempCal.getTime();
//ab.setTimeZone(PST);
Log.e (" fbu "," fsutc " + dateLocal + " / " + dateLocal2);
Log.e (" fbu "," fsutc " + ISODepDate + " / " + ISOArrDate);
}
catch (Exception a){
int aa = 1;
Log.e (" exception "," a " + a);
}
public static Calendar toCalendar(final String iso8601string)
throws ParseException {
Calendar calendar = GregorianCalendar.getInstance();
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
String s = iso8601string.replace(".000Z", "+00:00");
try {
s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
} catch (IndexOutOfBoundsException e) {
throw new ParseException("Invalid length", 0);
}
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
calendar.setTime(date);
return calendar;
}
4 - Finally, here is what I am using to "Display" the above 3 time categories in local time.
public String UTCtoLocal(Date indate, Boolean formatLong) {
Date utcDate = indate;
String result;
//Log.e( " utc "," indate " + indate);
/*utcDate = your own initialization here;*/
Date localDate = new Date(utcDate.getTime() + TimeZone.getDefault().getRawOffset());
//Log.e( " utc "," localdate " + localDate);
if (formatLong){
result = longd.format(localDate);
} else {
result = shortt.format(localDate);
}
return result;
The questions are, given the expectation that I store in UTC and display in Local, a) Have I implemented items 1-4 correctly? b) Will the above code actually store the times in UTC and display in local?
After flat file load everything looks good. After restart the times are displayed in UTC vs Local.

Only accept two or four digit years from users

I have to accept a date from a user via a simple inputText field (JSF 2). I created a Converter so I can validate the date and now I am running into trouble with 1, 3, and 5+ digit years. All dates entered by the user will be either today or in the future (up to a reasonable maximum).
The below solution accepts three different date formats and will correctly handle 2 and 4 digit years (in the former case by using set2DigitYearStart to convert them to 20XX). I am completely stumped how I can handle other wrong dates.
Code
public static void main(String[] args) throws Exception {
String date = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
System.out.println(formatter.parse(date));
break;
} catch (ParseException ignore) {
System.out.println("Date format doesn't match pattern: " + pattern);
}
}
}
Examples That Should be Accepted
02/02/02
02/02/2002
Examples That Should be Rejected
02/02/1
02/02/333
02/02/55555
One Approach
Get some theoretical maxDate and yesterday's date, then compare the output. This seems wrong somehow, though...
SimpleDateFormat f4 = new SimpleDateFormat("MM/dd/yyyy");
Date maxDate = f4.parse("01/01/2099");
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date minDate = f4.parse(dateFormat.format(cal.getTime()));
Add some specific validation after your parsing is finished to reject any years that are out of range ie getYear() < 1000 and getYear() > 9999
Warning this code is not compiled or tested as I am typing on a tablet.
String dateStr = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
Date date = null;
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
date = dateformatter.parse(dateStr));
break;
} catch (ParseException ignore) {
continue;
}
}
if (date != null) {
Calendar cal = new GregorianCalendar (date);
int year = cal.get(Calendar.YEAR);
if (year() < 1000 || year() > 9999) {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
}
} else {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
{

Using Java SimpleDateFormat to find max date

I haven't programmed in Java for many years, but I now have to change a program I wrote some time ago. In this program I need to read a QIF file and find the qif record with the maximum date (Dmm-dd-yyyy).
I could not get this to work in my program so I wrote a simple test to demonstrate the problem I am having. I think there are other ways to do this, like lists and collections. But I still want to know why using SimpleDateFormat won't work. Notice in the output that this method produces the max for July but seems to ignore all August dates.
Thanks, Mike
import java.text.SimpleDateFormat;
import java.util.Date;
class DateParser {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
Date nextDate = null;
Date maxDate = null;
String nextStrDate = null;
String maxStrDate = null;
//Fill date array.
String date[] = {"07-14-2014","07-22-2014","07-31-2014",
"08-01-2014","08-04-2014","08-06-2014"};
try {
//Start with early maximum date.
maxDate = sdf.parse("01-01-1800");
// Find Max date in array.
for (int i=0; i<6; ++i) {
nextStrDate = date[i];
nextDate = sdf.parse(nextStrDate);
if(nextDate.after(maxDate)){
maxStrDate = nextStrDate;
maxDate = nextDate;
}
System.out.println( "Next Date = " + nextStrDate);
}
System.out.println("\nMax Date = " + maxStrDate);
} catch (Exception e) {
System.out.println("Got error:" + e);
}
}
}
OUTPUT
Next Date = 07-14-2014
Next Date = 07-22-2014
Next Date = 07-31-2014
Next Date = 08-01-2014
Next Date = 08-04-2014
Next Date = 08-06-2014
Max Date = 07-31-2014
From the Java Docs....
m Minute in hour
What you want is
M Month in year
Change mm-dd-yyyy to MM-dd-yyyy
You format is incorrect, this
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
should be
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
because (per the SimpleDateFormat documentation),
Letter Date or Time Component Presentation Examples
...
M Month in year Month July; Jul; 07
...
m Minute in hour Number 30

get the right Month format date java

can any help, how to get the right date from an String like this "2014-01-10T09:41:16.000+0000"
my code is:
String strDate = "2014-01-10T09:41:16.000+0000";
String day = "";
String format = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
Locale locale = new Locale("es", "ES");
SimpleDateFormat formater = new SimpleDateFormat(format, locale);
formater.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
Calendar cal = Calendar.getInstance();
try {
cal.setTimeInMillis(formater.parse(strDate).getTime());
String offerDate = cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
System.out.println(offerDate);
} catch (Exception e){
System.out.println(e.getMessage());
}
in the result i give something like this: "10-0-2014", i want the result like that "10-01-2014"
thanks in advance :)
The documentation states:
java.util.Calendar.MONTH
MONTH public static final int MONTH Field number for get and set
indicating the month. This is a calendar-specific value. The first
month of the year in the Gregorian and Julian calendars is JANUARY
which is 0; the last depends on the number of months in a year.
-> Counting starts at 0 for Calendar.MONTH
I think the easiest would be to use another formatter object to do the formatting instead of building it yourself:
try {
Date d = new Date(cal.setTimeInMillis(formater.parse(strDate).getTime()));
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String offerDate = format.format(d);
System.out.println(offerDate);
} catch (Exception e){
System.out.println(e.getMessage());
}

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