I need to format my input date string.
Input date string : 28-01-1983(dd-MM-yyyy)
Expected date string : 1983-01-28 (yyyy-MM-dd)
I have used below program. But I am not getting correct output.
public static String formateDate(String oldFormat, String newFormat, String date) {
final String OLD_FORMAT = oldFormat;
final String NEW_FORMAT = newFormat;
String oldDateString = date;
String newDateString = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
}
catch (ParseException e) {
e.printStackTrace();
}
return newDateString;
}
Calling method :
public static void main(String[] args) {
String formatDob = formateDate("MM-dd-yyyy", "yyyy-dd-MM", "28-01-1983");
System.out.println("Formated DOB:"+formatDob);
}
Right now I am getting output : Formated DOB:1985-01-04
Why my code produce wrong output? I am using JDK 1.7
You are passing month as 28 in your old format which says (12 + 12 + 4) means April month of the upcoming third year.
So, your old format(MM-dd-yyyy) will parse date as (1983 + 2 years) = 1985 and 4th month of the third year which is April so you will have date 1st April 1985. Your old date format should be dd-MM-yyyy.
Consider the first part of the conversion
You have format of MM-dd-yyyy and you have the date string of 28-01-1983
As there is not a month 28 I suggest that the format should be dd-MM-yyyy
Change
formateDate("MM-dd-yyyy", "yyyy-dd-MM", "28-01-1983");
to
formateDate("MM-dd-yyyy", "yyyy-dd-MM", "01-28-1983");
Your were passing date in place month.
Related
In my application I want to show some text (date) into TextView.
I get this Text from server and I want to show this Text in TextView.
I get this Text from server :
16 Dec 2017
But I want to show such as this :
2017
How can I remove 16 Dec ?
try this
public static String getYyyy(String date) {
String time = date;
try {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
Date date1 = format.parse(date);
if (date1 != null) {
time = new SimpleDateFormat("yyyy").format(date1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
try this use split()
There are two signature for split() method in java string.
public String split(String regex)
and,
public String split(String regex, int limit)
use split a string in Java is to use .split(" ") which splits a string according to the pattern provided, returning a String array.
sample code
String date="16 Dec 2017";
String [] dateParts = date.split(" ");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
You can just separate the string with help of " " i.e. blank space, try to split the string with " " just like this:-
String date = "16 Dec 2017";
String[] date = date.split(" ");
//for only 2017 you can use date[2]
Be aware there are several ways more elegant and correct to do this, normally you use a Date object and just change how it looks like...
but to your wish, my answer:
I wouldnt split because is a waste to create an array for only getting one element of it...
you can use the substring method
String xdate = "16 Dec 2017";
System.out.println(xdate.substring(xdate.length() - 4, xdate.length()));
In java 8 you can do like this :
Date date = new Date(); //Create a Date object with date provided from TextBox
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Since you only want the year int year = localDate.getYear(); will give you year.
if you want substring of date in which only Year i.e. last 4 number then try below code
String date="16 Dec 2017";
int a = date.length();
String d = date.substring(a-4,a);
You can try this as well rather then split if you have date & time or more date data
String requested_date = "16 Dec 2017";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
Date dateObj = simpleDateFormat.parse(requested_date,new ParsePosition(0));
dateObj.getYear();
This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 5 years ago.
I am trying to parse string into a date using the following code:
public static Date dateFormatter(String s)
{
SimpleDateFormat ft = new SimpleDateFormat ("MMddYYYY");
Date excelDate=null;
try
{
excelDate = ft.parse(s);
Date formatString = ft.format(excelDate);
System.out.println("Date to be printed in Excel is :" +formatString);
return excelDate;
}
catch(Exception ae)
{
System.out.println("No date");
}
return excelDate;
}
I am passing in the argument "04202017".
This function is not working for me. I am not able to figure out what I am doing wrong. Can anybody please help me?
You have to use ft.parse(s); instead of format(excelDate). Format is the other way (Date -> String)
DateFormat.parse(String)
And you dont have to parse the Date back to a String.
Corrected code:
public static Date dateFormatter(String s) {
SimpleDateFormat ft = new SimpleDateFormat ("MMddYYYY");
Date excelDate = null;
try {
excelDate = ft.parse(s);
System.out.println("Date to be printed in Excel is :" +excelDate);
return excelDate;
} catch(Exception ae) {
System.out.println("No date");
}
return excelDate;
}
You already parsed String s to excelDate with date format that you want. So i think it's good and enough to print just excelDate.
System.out.println("Date to be printed in Excel is :" +excelDate);
Like that.
And also change MMddYYYY to MMddyyyy.
Try parse method instead of format
For String to Date, use:
SimpleDateFormat.parse(String);
For Date to String, use:
SimpleDateFormat.format(date);
However, in your code, you already parsed the String and assigned into excelDate on this line:
excelDate = ft.parse(s);
try this one:
String string = "march 9, 2017";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
It would be nice to use Java 1.8's new time classes (which are in java.time.* package).
public static void main(String[] args)
{
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// To String
String dateString = dateTime.format(formatter);
System.out.println(dateString);
// To LocalDateTime
LocalDateTime parsedLocalDateTime = LocalDateTime.parse(dateString, formatter);
}
I am writing Junit tests to verify data entered after it has been transformed into a different format. How would I convert a String like "1/1/1970" into a date object formatted like 19700101000000? I tried this:
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = format.parse("1/1/1970");
But "1/1/1970" throws an Unparseable date ParseException. Thanks!
You must use different DateFormats to parse and to format. Right now you're taking "1/1/1970" and trying to read it with the date format "yyyyMMddHHmmss". You'll need to parse with the format MM/dd/yyyy, get out a Date, and then format it with your format "yyyyMMddHHmmss".
You need to parse using one formatter, then reformat using another. Here's code for old style, and for new java.time API built into Java 8 and later.
String input = "1/1/1970";
// Using SimpleDateFormat
Date date = new SimpleDateFormat("M/d/yyyy").parse(input);
System.out.println(new SimpleDateFormat("yyyyMMddHHmmss").format(date));
// Using Java 8 java.time
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/d/uuuu"));
System.out.println(localDate.atStartOfDay().format(DateTimeFormatter.ofPattern("uuuuMMddHHmmss")));
As Louis Wasserman indicated, format.parse the input date String to a Date object. Then use that Date object as input to another SimpleDateFormat object.
Something like this :
public class DateFormatTest {
public static void main(String[] args) {
String inputDate = args[0];
java.util.Date d = null;
java.text.DateFormat inputDateFormat = new java.text.SimpleDateFormat("MM/dd/yyyy");
java.text.DateFormat outputDateFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
try {
d = inputDateFormat.parse(intputDate);
} catch (java.text.ParseException ex) {
System.err.println("something horrible went wrong!");
}
String output = outputDateFormat.format(d);
System.out.println("The input date of: " + inputDate + " was re-formatted to: " + output);
}
}
Providing "1/1/1970" as the input parameter, the output is:
The input date of: 1/1/1970 was re-formatted to: 19700101000000
In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);
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.