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
Related
In my SQLite database I have my dates stored in this format 02/01/2023 but when I try to get the date from the calendarview it gives them to me as 2/1/2023 which causes me to have an error when trying to retrieve the data from the database that matches that date.
How do I format this into a String variable?
My attempt so far:
public void onSelectedDayChange(#NonNull CalendarView calendarview, int i, int i1,int i2) {
exercise_name = new ArrayList<>();
set_weight = new ArrayList<>();
set_reps = new ArrayList<>();
set_date= new ArrayList<>();
//formatting to dd/mm/yyyy
System.out.println("both are over 10");
date = i2 + "/" + (i1+1) + "/" + i;
//month needs plus 1 because it starts at 0
tviewdate.setText(date);
storeDataDateinArrays();
There is a better way (than what you have posted as an answer) to get the required formatted string:
String output = String.format("%02d/%02d/%d", day, month, year);
where day, month and year are integers.
Using java.time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// Sample units
int year = 2023, month = 2, day = 1;
LocalDate date = LocalDate.of(year, month, day);
String output = date.format(formatter);
System.out.println(output);
}
}
Output:
01/02/2023
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
This is how i got it to work:
String sYear = String.valueOf(Year);
String sMonth = String.valueOf((Month + 1));
String sDay = String.valueOf(Day);
if (sDay.length() == 1)
sDay = "0" + sDay;
if (sMonth.length() == 1)
sMonth = "0" + sMonth;
if (sDay.length() == 1)
sDay = "0" + sDay;
date = sDay + "/" + sMonth + "/" + sYear;
I have this Date in a String with a 2 digit year.
I need to convert in another format. I tried with SampleDateFormat but it didn't work.
The SampleDateFormat is giving wrong format i.2 date with UTC and timestamp
I want in yyyy/MM/dd only.
Is there any other way to do this?
String receiveDate = "7/20/21";
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
rdate = sdf.parse(receiveDate);
} catch (ParseException e) {
e.printStackTrace();
}
String recievedt = rdate.toString();
String dateParts[] = recievedt.split("/");
// Getting day, month, and year from receive date
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];
int iday = Integer.parseInt(day);
int imonth = Integer.parseInt(month);
int iyear = Integer.parseInt(year);
LocalDate date4 = LocalDate.of(iyear, imonth, iday).plusDays(2*dueoffset);
If you can use the java.time API I would suggest something along the lines of the following:
String input = "7/20/21";
LocalDate receivedDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/dd/yy"));
String formatted = receivedDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
// or if you actually need the date components
int year = receivedDate.getYear();
...
How is String receiveDate="7/20/21"; a valid date?
String dateStr = "07/10/21";
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date)); // 2007/10/21
This, however, requires that you have date with leading zeros for year, month and date. If that is not the case, please sanitize your date string.
public static String sanitizeDateStr(String dateStr) {
String dateStrArr[] = dateStr.split("/");
String yearStr = String.format("%02d", Integer.parseInt(dateStrArr[0]));
String monthStr = String.format("%02d", Integer.parseInt(dateStrArr[1]));
String dayStr = String.format("%02d", Integer.parseInt(dateStrArr[2]));
return String.format("%s/%s/%s", yearStr, monthStr, dayStr);
}
public static void main (String[] args) throws Exception {
String dateStr = sanitizeDateStr("7/10/21");
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date));
}
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MM/dd");
String birthDate = format3.format(date);
try {
age = format3.parse(birthDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
if(age != null)
c.setTime(age);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date2 = c.get(Calendar.DATE);
LocalDate l1 = LocalDate.of(year,month,date2);
LocalDate now = LocalDate.now();
Period diff = Period.between(l1,now);
Integer age = diff.getYears();
String ageString = age.toString();
This would be my approach using LocalDate and DateTimeFormatter. It is not only shorter, but also less error-prone.
String inputDate = "1990/01/21";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate age = LocalDate.parse(inputDate, formatter);
Period diff = Period.between(age, LocalDate.now()); // outputs: 31 years
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
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.