I have written a small program in which a user enters minutes and program shows the current Date and Time + minutes entered by the user.
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, Integer.valueOf(sample.getMinutes()));
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println(" Date and time with added Minutes : " + (dateFormat.parse(dt));
Sample
private String minutes;
//getter and setter
I am getting this exception
java.lang.NumberFormatException: For input string: ""
What I am doing wrong here?
Should I use
Integer.parseInt
or
Integer.valueOf(Integer.parseInt(sample.getMinutes())));?
With current date and time.
public static void main(String[] args)
{
try
{
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
Date sample = new Date();
int iMinutes = 30;//minutes added by the user
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, Integer.valueOf(sample.getMinutes()));
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println("Current Date and time:"+sample);
System.out.println("Date and time with added Minutes : " + (dateFormat.parse(dt)));
}
catch (ParseException ex)
{
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
The output will be displays as:
Current Date and time:Tue Jun 12 15:57:55 IST 2012
Date and time with added Minutes : Tue Jun 12 16:54:55 IST 2012
Here the minutes "57" was added to the calendar and the time has moved forward by "30" mins.And that is the your result(Date and time with added Minutes).
With user in input minutes.
public static void main(String[] args)
{
try
{
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
int iMinutes = 30;//minutes added by the user
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, iMinutes);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println("Current Date and time:"+sample);
System.out.println("Date and time with added Minutes : " + (dateFormat.parse(dt)));
}
catch (ParseException ex)
{
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
This will work as per your desire first you take the minutes from the user and assign that minutes to the "iMinutes" variable of the code it will add that much minutes to the calander.
The output will be displayed as:
Current Date and time:Tue Jun 12 16:07:55 IST 2012
Date and time with added Minutes : Tue Jun 12 16:37:55 IST 2012
And if you want to set the minutes then use "set" instead of "add" in the "cal.add".
Hope this will solve your problem.
Regards.
Check if the returned string from sample.getMinutes() is a number or not. It must be a number without any white space to be parsed, otherwise you will get a NumberFormatException.
The problem you're having is that an empty string is not a valid integer. Your application should catch the exception, and set a sensible default instead.
"" is an empty string and it cannot be parsed into a valid integer given any circumstances
java.lang.NumberFormatException: For input string: ""
An empty String cannot be parsed to a number.
You need to check it first (using something like String#length() or StringUtils#isBlank()) and decide what to do with this case (for example treat it as zero).
java.lang.NumberFormatException: For input string: ""
Seems like you never set the minutes String
java.lang.NumberFormatException: For input string: ""
input String "" can not be converted into valid Integer.
before using Integer.parseInt, you ensure you are getting an integer by the following ways.
1.provide javascript validation for checking int
or/and
2.provide a server side validation for checking non-integer Strings
also see how to avoid NumberFormatException
Add some sort of checking:
final String DATE_FORMAT_NOW = "MM/dd/yyyy HH:mm:ss";
final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
Calendar cal = Calendar.getInstance();
final String minutes = sample.getMinutes()
cal.add(Calendar.MINUTE, Integer.valueOf((minutes != null && !minutes.isEmpty()) ? minutes : 0);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String dt = sdf.format(cal.getTime());
System.out.println(" Date and time with added Minutes : " + (dateFormat.parse(dt));
There is nothing unusal here. Read the java docs for parseInt() and valueOf which clearly states that a NumberFormatException is thrown if the String does not contain a parsable integer. And an empty string "" is not a parsable int.
It is up to you how you handle such cases for which a NumberFormatException is thrown.
Related
I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017 "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...
Let's have the following:
Date inDbDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
inDbDate = sdf.parse("2015-09-27 23:24:28.035");
Now, when I output the inDbDate I receive the following:
Sun Sep 27 23:24:28 EEST 2015
So, If I have two dates with millisecond differences, there would be no way to find out or to display it.
How do I compare two Dates with this format - 2015-09-27 23:24:28.035 ?
If you want to compare two Date variables, there are some methods provided after(), before(), equals().
private void someMethod(){
final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date firstDate = new Date();
Date secondDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
firstDate = sdf.parse("2015-09-27 23:24:28.035");
secondDate = sdf.parse("2015-09-27 23:24:28.036");
} catch (ParseException pe) {
pe.getMessage();
}
if(firstDate.after(secondDate)) {
System.out.println("The first date is after the second date");
} else{
System.out.println("The first date is before the second date");
}
}
You can copy and paste the above method into your IDE, then try changing the time in the Date variables and see what the outcome is as well as changing the check performed in the if statement.
If you look at the values in one of the Date objects in your debugger you can see the milliseconds are there, just not shown when printed out in a certain format.
1/ you should parse inDbDate with date format ==> inDbDate = sdf.parse("2015-11-11 23:24:28.035");
2/ you can now compare the two dates
if (inDbDate.compareTo(new Date()) > 0) {
System.out.println("inDbDate is after the current date !!");
}
3/ if you want to display, you format it
System.out.println("current time = " + sdf.format(new Date()));
I have 2 strings: "Sun Jun 23" and "22:45". I want to get the long (millisecond?) representation of the date that is indicated by this 2 strings plus the actual year.
I am trying something like this:
String s1 = "Sun Jun 23";
String s2 = "22:45";
long date = new SimpleDateFormat("EEE MMM dd").parse(s1).getTime()
+ new SimpleDateFormat("HH:mm").parse(s2).getTime();
When I convert back the long date format to String with
private SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
console.getOut().println(sdf.format(date));
I got "1970.06.23_20:45:00"
This indicates 2 problems:
This doesn't contain the current year. How can I add it?
Why did I 'lost' 2 hours (from 22:45 to 20:45)
Try concat the string then parse the date and get the time
String completeTime = s1 + " " + s2;
SimpleDateFormat sdf = new SimpleDateFormat ("EEE MMM dd HH:mm")
Date date = sdf.parse(completeTime)
long millis = date.getTime()
Edit..
Completely did read the whole question before sorry...
The year is not read in anywhere by your date so you will either have to add it or read it in from somewhere, if it is the year, I suggest using a Calendar object to get it
The Timezone information in the parse from your millis long seems to causing the time difference, you could try using "GMT+2" to correct this but this may not always be correct. If you take out the settin gof the timezone does it change your result?
I got a bit further, but got a different issue:
String s1 = "Sun Jun 23";
String s2 = "22:45";
SimpleDateFormat f = new SimpleDateFormat("YYYY EEE MMM dd HH:mm");
f.setTimeZone(TimeZone.getTimeZone("GMT")); //thanks for the timezone hints!
Date d;
long date;
int year;
try {
year = Calendar.getInstance().get(Calendar.YEAR);
String fullDate = year + " " + s1 + " " + s2;
d = f.parse(fullDate);
date = d.getTime();
SimpleDateFormat sdf2;
sdf2 = new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("GMT"));
console.getOut().println(sdf2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
This prints out:
2012.12.30_22:45:00.
Timezone now looks okay (as I see 22:45),
fullDate contains the proper string ("2013 Sun Jun 23 22:45").
Why do I not get the correct date?
I know how to use file.lastModified();.
When I println that I get (for example): Sat Mar 17 09:24:33 GMT+01:00 2012.
But is it possible that I only get the day, month and year as numbers, for example: 17 03 2012
Is their a way to do this, maybe a filter, or an other function to get last modified date in numbers?
is file a java.io.File object?
lastModified should return time in milliseconds. You can create a Date object with the lastModified return value and the format the output with a SimpleDateFormat
Date date = new Date(file.lastModified());
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("d M y");
System.out.println(sdf.format(date));
You can use SimpleDateFormat class, i.e.
package com.example.file;
import java.io.File;
import java.text.SimpleDateFormat;
public class GetFileLastModifiedExample
{
public static void main(String[] args)
{
File file = new File("\\somefile.txt");
System.out.println("Before Format : " + file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("After Format : " + sdf.format(file.lastModified()));
}
}
Try this,
long longDate = file.lastModified();
Date date = new Date(longDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String newDate = formatter.format(date);
System.out.println("Formatted date " + newDate);
according to the documentation
File.lastModifed()
should return a long value representing the time the file was last modified, measured in milliseconds since the epoch. Yon can use the long value in conjunction with Calendar
Calendar rightNow = Calendar.getInstance()
rightNow.setTimeInMillis(longValue)
and use rightNow.get(...)
to retrive day, month and year
I have this as a string 02/06/2012 1:25 PM EST
I want to use SimpleDateFormat to return "Feb" from that data
Here is what I tried
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
String month = "";
try {
month = gottenDate.format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately gottenDate.parse("02/06/2012 1:25 PM EST") gets a parse exception when the SimpleDateFormat documents say it should work.
If I do SimpleDateFormat gottenDate = new SimpleDateFormat("MM"); with two M's instead of 3, it returns "02" for me, as expected. The documents say that 3 or more M's should return a textual month. This doesn't happen, why? And yes, by now I could have made a string array of months and matched them to the numberic month SDF returned for me, but I am curious.
How do I make it work for me, thank you!
Exception is expected in your case:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("02/06/2012 1:25 PM EST");
"gottenDate" is set up to parse a string if it matches "MMM" pattern. The following should work:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("Feb");
Hopefully you can see what's going on here.
You need a format to parse the date: MM/dd/yyyy, and once you have a Date object from this first date format, you need a second one: MMM, to format the date as you want.
Formatting with MM will give you the month on two digits, and parsing with MMM will expect an abbreviated textual month, and won't parse 02.
You need two separate SimpeDateFormat instances with corresponding format strings to parse source date and format it back into short month form. Your format instance can't parse full date because it expecting only month in specified string.
SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
SimpleDateFormat gottenDate = new SimpleDateFormat("dd/MM/yyyy h:mm a z");
String month = "";
try {
month = monthDate .format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Not sure about format of your source string, complex format strings are little tricky.
This is the code that will get MonthName to you:
public String getMonthName(String dtstr, String fmt) throws ParseException {
SimpleDateFormat gottenDate = new SimpleDateFormat(fmt);
SimpleDateFormat month = new SimpleDateFormat("MMM");
Date dt = gottenDate.parse(dtstr);
return month.format(dt);
}
Call it like this:
System.out.println(getMonthName("01/06/2012 1:25 PM EST"), "M/d/y");
OUTPUT:
Feb
Well, others were faster answering, but I think this will do what you want.
String date_str = "02/06/2012 1:25 PM EST";
SimpleDateFormat in_format = new SimpleDateFormat("MM/dd/yyyy h:mm aa zzz");
SimpleDateFormat out_format = new SimpleDateFormat("MMM");
Date my_date = in_format.parse(date_str);
String out_str = out_format.format(my_date);
System.out.println(out_str); // Prints Feb
Dates and times can get complicated because of the way people in different record times. The best reference I've found for understanding all this is here:
http://www.odi.ch/prog/design/datetime.php
Just to provide an alternative solution, since your jobs is to "extract" the month of a Date, I think Calendar best fits the job.
// Construct a Date object
final DateFormat df = new SimpleDateFormat("M/d/y");
final Date originalDate = df.parse("02/06/2012 1:25 PM EST");
final Calendar c = Calendar.getInstance();
c.setTime(originalDate); // set the calendar Date
// Extract the month
String month = c.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
System.out.println(month);