How to Convert String into Integer
I have a String like String date is equal "2020-03-18" , I want to convert this String into int .
may be if you want convert string date to int :
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(yourDateString);
return parsedDate.getTime();
} catch(Exception e) { //this generic but you can control another types of exception
// look the origin of excption
}
If you need to convert this String to Date:
String date="2020-03-18";
Date date1=new SimpleDateFormat("yyyy-MM-dd").parse(date);
System.out.println("Date: "+date1);
From this date you have other methods that you could get data from this Date Object ex:
date.getYear() //would reuturn 2020 - 1900 - Year
date.getMonth() // which counts from 0 to 11 - January is 0 example
date1.getDate() // would return 18
Full code:
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author besartm
*/
public class StringToDate {
public static void main(String[] args) {
String date="2020-03-18";
Date date1;
try {
date1 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
System.out.println("Date: "+date1);
System.out.println("Year: "+date1.getYear());
System.out.println("Month: "+date1.getMonth());
System.out.println("Day: "+date1.getDate());
} catch (Exception ex) {
}
}
}
If you want to convert String into an int:
int num = Integer.parseInt("2018");
If you want to convert String into Date:
import java.text.SimpleDateFormat;
import java.util.Date;
public class HelloWorld {
public static void main(String[] args)throws Exception {
String date = "2020-03-18";
Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
System.out.println(date1);
}
}
I post here example you can run and try for yourself. I converted the input string to Date object and then to number of milliseconds. However int
type is not large enough to hold that value, so I advise to use long
.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToInt
{
public static void main(String []args) throws Exception
{
String dateString = "2020-03-18";
Date dateObject = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
System.out.println("date: " + dateObject);
// int cannot hold that value, overflow happens
int int_millis = (int) dateObject.getTime();
// long type is better for that
long long_millis = dateObject.getTime();
System.out.println("int: " + int_millis);
System.out.println("long: " + long_millis);
}
}