I have 3 int variables for Month, Day and Year.
How can I convert them to a java.util.Date object (or whatever).
For Example, Month = 12, Date = 20, Year = 2011
It should be print in medium date format: **Dec 20, 2011**
Thank you very much!
Edit here my try:
String yourBirthDay = Integer.toString(birthMonth) + "." + Integer.toString(birthDay) + "." + Integer.toString(birthYear);
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
try {
Date date = format.parse(yourBirthDay);
System.out.println("Your birth date is : " + date.toString());
} catch (ParseException pe) {
System.out.println("ERROR: could not parse date in string \""
+ yourBirthDay + "\"");
}
I did this little test using Calendar.set(int year,int month, int date):
#Test
public void testDate() throws ParseException {
int year = 2011, month = 12, date = 20;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, date);
Date javaDate = calendar.getTime();
// SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM);
String stringDate = format.format(javaDate);
assertEquals("Dec 20, 2011", stringDate);
}
You need to remove 1 from the month because java.util.Calendar works with zero based months.
Related
I have a string in which I am finding the datetime with milliseconds as follows:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if(monthup.length()==1){monthup="0"+monthup;}
if(dayup.length()==1){dayup="0"+dayup;}
if(hourup.length()==1){hourup="0"+hourup;}
if(minuteup.length()==1){minuteup="0"+minuteup;}
if(secondup.length()==1){secondup="0"+secondup;}
if(millisup.length()==1){millisup="0"+millisup;}
if(millisup.length()==2){secondup="00"+millisup;}
String timewithmilsec = year+ monthup + dayup+ hourup+ minuteup+ secondup+ millisup;
System.out.println(timewithmilsec);
I am getting a value: 20151020115216690 which is obviousely correct.
I want to parse it to java Date format.
What I did is as follows:
try{
DateFormat formatter = new SimpleDateFormat("yyyyMMdHHmmssaaa");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
}
catch(Exception e){
System.out.println(e);
}
I am getting an error as follows:
java.text.ParseException: Unparseable date: "20151020115247995"
You have only one d in your format, but are padding the day to two characters, also, according to the JavaDocs...
a Am/pm marker Text PM
which isn't a millisecond place holder, I think you mean SSS
For example...
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if (monthup.length() == 1) {
monthup = "0" + monthup;
}
if (dayup.length() == 1) {
dayup = "0" + dayup;
}
if (hourup.length() == 1) {
hourup = "0" + hourup;
}
if (minuteup.length() == 1) {
minuteup = "0" + minuteup;
}
if (secondup.length() == 1) {
secondup = "0" + secondup;
}
if (millisup.length() == 1) {
millisup = "0" + millisup;
}
if (millisup.length() == 2) {
secondup = "00" + millisup;
}
String timewithmilsec = year + monthup + dayup + hourup + minuteup + secondup + millisup;
System.out.println(timewithmilsec);
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
} catch (Exception e) {
System.out.println(e);
}
Which for me prints
20151020173034124
Tue Oct 20 17:30:34 EST 2015
And while I'm at it, let me introduce you to String.format, which can reduce all you int to String conversion and padding code down to...
String timewithmilsec = String.format("%04d%02d%02d%02d%02d%02d%03d", year, month, day, hour, minute, second, millis);
I am getting Tue Oct 20 12:04:08 IST 2015 but interestingly I did not see any millisecond here
Date#toString won't include the milliseconds by default, you will need to supply a DateFormat which can.
If I replace the last System.out.println with System.out.println(new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS").format(date)); it prints something like
20 Oct 2015 17:37:14.856
(for the value 20151020173714856)
According to documentation letter S responds to milliseconds so your format should look like this new SimpleDateFormat("yyyyMMddHHmmssSSS"); (you have one d in your format).
The answer is the missing "d" in the date format, where #MadProgrammer depicts.
In addition, the generation of the string representation of the date should be reconsidered. You should use SimpleDateFormat.format() to generate date string as in the sample code below:
Calendar now = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String formattedDate = formatter.format(now.getTime());
System.out.println("Formatted date: " + formattedDate);
And the output will be in a format that you requested.
Formatted date: 20151020094934279
In my code I want to have the individual numbers from date format so I can use them as int values:
public static final String DATE_FORMAT = "dd.MM.yyyy";
public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}
also I would like some user input to define day,month and year in one go, if that's even possible:
private Date dateOfPublication;
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}
I hope you can help me out, previously I did it all seperatly but the code was quite big and I think it would be prettier if I could do it like that..
update: okay I'm doing the input like this now:
System.out.print( "Please enter dateOfPublication, use format of x.x.xxxx: " );
userInputDate = scn.next();
String[] ary = userInputDate.split("\\.");
publicationDay = Integer.parseInt(ary[0]);
publicationMonth = Integer.parseInt(ary[1]);
publicationYear = Integer.parseInt(ary[2]);
thanks for your help!
Take a look at Java 8's new Time API (or JodaTime or Calendar if you're really stuck)
LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());
Which outputs
2015-10-16
16
10
2015
Now, you could simply ask the user to input a date in a given format and try and parse the result, if the parsing fails, you could reprompt them
For example...
Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {
System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();
try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}
} while (ld == null);
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());
You can use:
dateFormat.format(today).split("\\.");
For your code:
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
String[] dateArr = dateFormat.format(today).split("\\.");
int currentnDay = Integer.parseInt(dateArr[0]);
int currentMonth = Integer.parseInt(dateArr[1]);
int currentYear = Integer.parseInt(dateArr[2]);
IdeOne Example
First, you have to parse the input string
The Calendar data type is more flexible for date-time handling. This is an example that shows some Date/Calendar operations.
Date date;
Calendar c;
// Get the current date
c = Calendar.getInstance();
System.out.println("Current Calendar:" + c.getTime().toString());
int currentnDay = c.get(Calendar.DATE);
int currentMonth = c.get(Calendar.MONTH);
int currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Current Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
String DATE_FORMAT = "dd.MM.yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse("11.10.1981");
System.out.println("Modified Date:" + date.toString());
// reset Calendar
c = Calendar.getInstance();
// set date to the calendar
c.setTimeInMillis(date.getTime());
currentnDay = c.get(Calendar.DATE);
currentMonth = c.get(Calendar.MONTH);
currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Modified Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
This is the output of the example.
Current Calendar:Thu Oct 15 20:22:59 EDT 2015
Current Values: 15/9/2015
Modified Date:Sun Oct 11 00:00:00 EDT 1981
Modified Values: 11/9/1981
Hi I am Calling below function to find time elapsed, till that date, It is working fine for all but following input : 12:46:21 PM
public Long timeDifference(String weboutput) {
try {
Calendar calendar = GregorianCalendar.getInstance();
Calendar today = new GregorianCalendar();
Date inputTime;
if (weboutput.length() <= 10) { // for data fetched for current date.
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a", Locale.US);
inputTime = formatter.parse(weboutput);
calendar.setTime(inputTime);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
today.setTime(new Date());
today.set(Calendar.HOUR, hour);
today.set(Calendar.MINUTE, minute);
today.set(Calendar.SECOND, second);
} else {
if (weboutput.length() <= 15) { // for data for earlier date in same year or month.
DateFormat formatter = new SimpleDateFormat("MMM dd hh:mm a", Locale.US);
inputTime = formatter.parse(weboutput);
calendar.setTime(inputTime);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
today.setTime(new Date());
today.set(Calendar.HOUR, hour);
today.set(Calendar.MINUTE, minute);
today.set(Calendar.MONTH, month);
today.set(Calendar.DATE, date);
} else { // for data with different year.
DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
inputTime = formatter.parse(weboutput);
calendar.setTime(inputTime);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int year = calendar.get(Calendar.YEAR);
today.setTime(new Date());
today.set(Calendar.HOUR, hour);
today.set(Calendar.MINUTE, minute);
today.set(Calendar.SECOND, second);
today.set(Calendar.YEAR, year);
today.set(Calendar.MONTH, month);
today.set(Calendar.DATE, date);
}
}
Date retrivedDate = today.getTime();
Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
difference = currentDate.getTime() - retrivedDate.getTime();
System.out.println(retrivedDate);
System.out.println(currentDate);
System.out.println(difference);
} catch (ParseException e) {
e.printStackTrace();
}
return difference;
}
public boolean alarmValue(Long alarmTime) {
if (alarmTime <= 1800000) // change this value for Alarm duration, currently 30 min = 30* 60 s = 1800 * 1000 ms = 1800000 ms.
return false;
else
return true;
}
the error is as follows:
java.text.ParseException: Unparseable date: "12:46:21 PM"
at java.text.DateFormat.parse(DateFormat.java:357)
at rcm.Selenium.Test.Calculations.timeDifference(Calculations.java:29)
at rcm.Selenium.Test.RcmSeleniumTest.main(RcmSeleniumTest.java:89)
Exception in thread "main" java.lang.NullPointerException
at rcm.Selenium.Test.Calculations.alarmValue(Calculations.java:76)
at rcm.Selenium.Test.RcmSeleniumTest.main(RcmSeleniumTest.java:90)
Kindly help me with this.
"12:46:21 PM" has 11 digits and therefore doesn't pass your first test (which is for <= 10 digits) for the format "hh:mm:ss a".
How to find previous date if current date is given as a String? Below is given my code. Is there any shorter solution?
private static String previousDay(String date) {
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String newDate = "";
if (day > 1 & month > 1)
newDate = year+"-"+month+"-"+(day-1);
else if (day == 1 & month > 1) {
Calendar calendar = new GregorianCalendar(year,month-1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+(month-1)+"-"+daysInMonth;
} else if (day == 1 & month == 1) {
Calendar calendar = new GregorianCalendar(year,12, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
newDate = year+"-"+12+"-"+daysInMonth;
}
return newDate;
}
You need to convert your String to Date, in order to do date calculations. You can use Calender to find previous day. From your code, I assume, your date format is yyyy-MM-dd.
String input = "2009-09-30";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = dateFormat.parse(input);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(myDate);
cal1.add(Calendar.DAY_OF_YEAR, -1);
Date previousDate = cal1.getTime();
Date currentDate= new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
Date previousDate = calendar.getTime();
// dccTimeStamp is "20120122121212"
String dccTimeStamp is "20120122121212"
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date dcc = sdf.parse(dccTimeStamp);
log.debug("Dcc Date is " + dcc.toString());
From this point on you can use Date (or Calendar) utilities and perform the Date operation you need.
I have this simple code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-10-29");
calendar.setTime(date);
Log.d("Debug","Day of the week = "+(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY));
The 29th of October is a Saturday so why do I get false?
Here is an example of how this could happen...
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse("2011-10-29");
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
System.out.println("Day of the week = "
+ (calendar.get(Calendar.DAY_OF_WEEK)));
System.out.println("Saturday? "
+ (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));
try {
date = format.parse("2011-10-29");
} catch (ParseException e) {
e.printStackTrace();
}
calendar = Calendar.getInstance(TimeZone.getTimeZone("PST"));
calendar.setTime(date);
System.out.println("Day of the week = "
+ (calendar.get(Calendar.DAY_OF_WEEK)));
System.out.println("Saturday? "
+ (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));
which outputs
Day of the week = 7
Saturday? true
Day of the week = 6
Saturday? false
so yes, depending on what time zone you are in it will or will not be Saturday.
Getting true with the following code:
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-10-29");
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY);
}
catch(Exception e) {
e.printStackTrace();
}
Maybe a locale setting?