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?
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 ...
This question already has answers here:
Java date is not preserving milliseconds in conversion with simple date format
(5 answers)
Closed 7 years ago.
Basically I'm attempting to parse date/time to Java, but having issues when trying to parse the milliseconds.
Example of data to be parsed: a[0] = 16/03/2015, a[1] = 10:00:18.120
I read in the two values and concatenate them.
Getting: dateTime = (java.lang.String) "16/03/2015 10:00:18.120"
As you can see the string has the milliseconds when i debug it. From here I parse it to SimpleDateFormat. It works- however the milliseconds are not displayed
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime;
dateTime= a[0]+" "+a[1];
Date d = df.parse(dateTime);
Current output: d = (java.util.Date) Mon Mar 16 10:00:18 GMT 2015
Thanks for your help.
Your code is fine, but not your interpretation of the result. As correctly mentioned in one comment, the method toString() of class java.util.Date does not output the millisecond part. But the millisecond part is still part of the state of your result object. Proof:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = "16/03/2015 10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(d); // Mon Mar 16 10:00:18 CET 2015
System.out.println(d.getTime()); // 1426496418120
System.out.println("millisecond-part=" + (d.getTime() % 1000)); // millisecond-part=120
So all is fine. You can even format your result back to a string using the same (or another instance of SimpleDateFormat - maybe with different pattern, locale and timezone).
If java.util.Date was correctly implemented as value-type then the inventors of that class would have taken care of making the output of toString() representing the whole exact state of the object but it has not happened - another example why this class is broken.
Using DateFormat.format(Date date) function might meet your requirement
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime=df.format(date);
String[] a=dateTime.split(" ");
System.out.println(a[0]+" "+a[1]);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime= "03/16/2015"+" "+"10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(df.format(d));
Try this:
String[] a = new String[]{"16/03/2015", "10:00:18.120"};
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = a[0] + " " + a[1];
try {
Date d = df.parse(dateTime);
System.out.println(d.getTime());//Returns milliseconds
} catch (ParseException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
The result: 1426492818120
I have to compare two dates whose format is yyyy-MM-dd HH:mm:ss. I know the way to compare date only the before or after date function.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String expiryTime = "2014-09-10 00:00:00";
But what's the best way to compare date and time with the current date and time.
Like we have two dates 2014-09-10 00:00:00 and current date with time is 2014-08-31 10:37:15. And now we have to compare it. How we can do that.
Any help is appreciated.
Convert the Date String to java.util.Date object using SimpleDateFormat and compare those date objects with Date#after or Date#before methods.
In java 8 - using new Java Time API, parse date String using DateTimeFormat and get LocalDate object and compare them.
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
final LocalDate dt1 = dtf.parseLocalDate(dateString1);
final LocalDate dt2 = dtf.parseLocalDate(dateString2);
final boolean check = dt1.isAfter(dt2);
if(check)
System.out.println(dt1 +" is after "+dt2);
else
System.out.println(dt2 +" is after "+dt1);
If I understand what you're trying to do you want to use a SimpleDateFormat (and you posted a good pattern) to parse the String(s) into Date(s) and then Date.before(Date). Putting that together into something like,
DateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String firstStr = "2014-09-10 00:00:00";
String secondStr = "2014-08-31 10:37:15";
Date first = sdf.parse(firstStr);
Date second = sdf.parse(secondStr);
boolean before = (first.before(second));
System.out.printf("%s is before %s",
before ? firstStr : secondStr,
before ? secondStr : firstStr);
Output is
2014-08-31 10:37:15 is before 2014-09-10 00:00:00
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} catch (ParseException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str1 = "2014-09-10 00:00:00";
Date date1 = formatter.parse(str1);
String str2 = "2014-08-31 10:37:15";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
System.out.println("date2 is Greater than my date1");
}
I have created a web service which returns the date of an event which is initially captured by the getDate() function. I want the date returned by this function (something along this format : 2013-05-17 14:52:00.943) to be parsed and shown to the user in the DD-MM-YYYY format.
Any suggestions? I haven't found any solution along this direction yet.
I have tried this code and it's work fine for me,Please Try my code below: Please upvote to Tarun also coz he gave almost right answer.just he did mistake that he passes cal.getTime() method instead of pDate
String formatDate = p.format(pDate);
and second mistake in format like"DD-MM-YYYY" but actual format is:
"dd-MM-yyyy" not "DD-MM-YYYY"
I have done changes in it and modify it.
String dateStr = "2013-05-16 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); // your web service format
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy"); // your required format
String formatDate = p.format(pDate); // convert it in your required format
SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); // Day format as you want EEE for like "Sat" and EEEE for like "Saturday"
String Day = formatter.format(pDate); // This will give you a day as your selected format
System.out.println("Date & Day>>>"+formatDate+" "+Day);
// For GMT format your format should be like this: "2013-05-16 14:52:00.943 GMT+05:30"
// Give it to me in GMT time.
c.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println("GMT time: " + c.format(pDate));
Output:
Date & Day>>>16-05-2013 Thursday
GMT time: 2013-05-16 02:52:00.943 Greenwich Mean Time
Joda time:
you can download 2.0 jar file of joda time from here:
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter
.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date2 = jodaParsed.toDate();
System.out.println("Date & Day:" + jodaParsed.getDayOfMonth() + "-" + jodaParsed.getMonthOfYear() + "-" + jodaParsed.getYear() + " " + jodaParsed.getHourOfDay() + ":" + jodaParsed.getMinuteOfHour()+" "+jodaParsed.dayOfWeek().getAsText());
output:
Date & Day:17-5-2013 16:27 Friday
Hope it will work for you.
String dateStr = "2013-05-17 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy");
String formatDate = p.format(pDate);
You can use Joda Time if you have colon in time offset.
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date = jodaParsed.toDate();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.get(Calendar.DATE));
More info about joda can be found here.
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Example:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("05/18/2013");
System.out.println(format2.format(date));
Output:
11-05-2013
Edit:
Calendar cal = Calendar.getInstance();
cal.setTime(specific_date);
int dayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
String dayOfMonthStr = String.valueOf(dayOfMonth);
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.