How to join integer value with character value [duplicate] - java

This question already has answers here:
Take int of day, month, year and convert to DD/MM/YYYY
(2 answers)
Closed 4 years ago.
I want the date to display together with forward slash without any space. If I run the below program, it will only display month's value. Please help.
int month, day, year;
public int displayDate()
{
int date = month/day/year;
}
System.out.printf("Date: %d%n", d.displayDate());

Simplistic Answer
You can use a String to append three int values
e.g.
int month, day, year;
public String displayDate()
{
return String.format ("%d/%d/%d", month,day, year);
}
System.out.printf("Date: %s%n", d.displayDate()); // change this as well
Of course this code has no bound checking

In your code, you are dividing month, day and year with the operator /.
In Java, there is a class SimpleDateFormat to format and display dates.
Try the following code:
public String displayDate(int month, int date, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, date);
return new SimpleDateFormat("MM/dd/yyyy").format(calendar.getTime());
}
It will return your date in the format MM/dd/yyyy as a String.
Note that month is zero-based.
Check this link out to get some more information about the format: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

As the documentation clearly states, Character.getNumericValue() returns the character's value as a digit.
It returns -1 if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character object, you'll need to unbox it first:

import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
DateDemo d = new DateDemo();
System.out.printf(d.displayDate()); //Output: 04/04/2018
}
public String displayDate()
{
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
return date;
}
}

Related

calling String value of date in another class as Date variable

I have a date of birth in string in Date class and I want to call it as Date variable in another class using constructor, HealthProfile as per my uml diagram. How can I do that? And also, what is the Scanner input type for Date? I have done other parts and below code is my getDateString method in Date class.
public String getDateString()
{
String dob = String.valueOf(day) + month + String.valueOf(year);
return dob;
}
The date of birth format I was trying to print is, example: 8 October 2000. I have a txt file of such data and trying to call from it.
java.util.Scanner hasn’t got a method for reading an instance of your Date class (it may be obvious). I suggest that you use
nextInt() for reading the day of month (e.g., 8)
next() for reading the month name (e.g., October)
nextInt() for reading the year (e.g., 2000)
With the three values thus obtained you can call your constructor Date(int day, String month, int year). As you may know, a Scanner can read from a text file.
Aside from this (ignore if you can’t use it):
For the conversion back to a string I suggest that you put spaces between the elements to get like 8 October 2000 again rather than 8October2000, which is unpleasant to read.
One may consider an enum for the months. It will complicate input, but will provide validation that a correct month name is entered. If this is not part of your requirement, you may leave this comment for other readers.
For production work one would use LocalDate from java.time, the modern Java date and time API, and not develop one’s own Date class.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I help you to create a Date Class with a contruct method.
In main class, i help you to use System.in to input data string and return what you method want.
Date Class:
public class Date {
int year;
String month;
int day;
public Date(int year, String month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
/**
* Getter and Setter methods
*/
public String getDateString(){
String dob = String.valueOf(day) + month + String.valueOf(year);
return dob;
}
Test main class:
public static void main(String[] args) throws ParseException {
Scanner scanner = new Scanner(System.in);
String inputstr = scanner.nextLine(); //you enter 24-07-2020
String[] inputarr = inputstr.split(" ");
Date date = new Date(Integer.valueOf(inputarr[2]), inputarr[1], Integer.valueOf(inputarr[0]));
System.out.println(date.getDateString());
}

Use Custom Method to Display date in form mm/dd/yyyy from return output

I need to create a method that will display the date in format mm/dd/yyyy when the method is accessed through a printf statement. This is an assignment and I cannot use java.util.Date Class.
The date value must be returned through the method so it can be printed with
System.out.printf("Date 1 is %s%n%n", date1.displayDate())
I have tried converting the instance variables for month, day, and year to Strings and then putting the String values into an array but when I do that all I'm getting is the first value of each of the indexes printed into the returned value.
I need to have the whole date in format mm/dd/yyyy returned but I'm not sure if I can iterate the entire array and then save that value into a variable to return.
Here is my driver class...
public class DriverClass {
public static void main(String[] args) {
//--------------------------------------------------------------------------------------
// DATE CLASS FUNCTIONALITY TEST
//--------------------------------------------------------------------------------------
DateClass date1 = new DateClass(07,21,1987);
DateClass date2 = new DateClass(01, 22, 1999);
DateClass date3 = new DateClass(04,17,1945);
System.out.printf("Date 1 is %s%n%n", date1.displayDate());
System.out.printf("Date 2 is %s%n%n", date2.displayDate());
System.out.printf("Date 3 is %s%n%n", date3.displayDate());
}
}
Here is my code...
public class DateClass {
private int month;
private int day;
private int year;
public DateClass(int monthIn, int dayIn, int yearIn){
month=monthIn;
day=dayIn;
year=yearIn;
}
//get and set methods
public int getMonth(){
return month;
}
public void setMonth(int month){
this.month=month;
}
public int getDay(){
return day;
}
public void setDay(int day){
this.day=day;
}
public int getYear(){
return year;
}
public void setYear(int year){
this.year=year;
}
public String[] displayDate(){
String sMonth = Integer.toString(month);
String sDay = Integer.toString(day);
String sYear = Integer.toString(year);
String dayAR[] = new String[5];
dayAR[0] = sMonth;
dayAR[1] = "/";
dayAR[2] = sDay;
dayAR[3] = "/";
dayAR[4] = sYear;
return dayAR;
}
}
Your displayDate() method should return a String instead of a String[].
return sMonth + "/" + sDay + "/" + sYear;
This won't quite work though, you would also need to do some bounds checking so that the values can be padded with zeros. For instance you want 01/01/0001 not 1/1/1.
I would avoid implementing a bunch of bounds checking though, just use an existing tried-and-true method for formatting strings. I suggest using String.format(format, ...args) to do the heavy lifting unless explicitly disallowed.
return String.format("%02d/%02d/%04d", month, day, year);
This solution still isn't perfect, it doesn't account for values that are not valid, but that should be done when the values are being set, not when the string is being generated.
You can use String.format to help get the formatting right. For example:
String.format("%d/%d/%d", 1, 20, 1995); // Produces "1/20/1995"
The documentation for Java String format syntax (like the %d and %s) is here.
You'll probably want to prefix days and months with a zero if they are only a single digit.
(Just wanted to give a hint since this is an assignment but let me know if you get stuck)

Comparing dates not working in java [duplicate]

This question already has an answer here:
What is the difference between JAVA date format "dd/MM/yyyy" and "dd/mm/yyyy"? [duplicate]
(1 answer)
Closed 6 years ago.
public static void main(String [] args){
String date = "01/08/2017";
Date todaydate = new Date();
SimpleDateFormat myFormat = new SimpleDateFormat("dd/mm/yyyy");
try {
Date expiry = myFormat.parse(date);
if(expiry.compareTo(todaydate) >0){
System.out.println("false");
}
else{
System.out.println("true");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
I am comparing date 01/08/2017 to current date. It should return false. However, it is returning true, even if I use isAfter in the if condition.
This should do the trick
SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy");
besides the format, compareTo() is returning true, always that the date is after the argument, which is right. If the dates where equals it would return 0.
Check the docs: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo%28java.util.Date%29
The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
you need to change the condition
if(expiry.compareTo(todaydate) <0)
Go to this link n see the methods of the dates
https://www.tutorialspoint.com/java/util/date_compareto.htm

How can I get the year from a Date object without using deprecated methods?

I've been given an assignment where I need to create a set of interfaces and classes for a car rental company. I'm busy working on implementing a LicenceNumber class which must match the following spec:
The licence number has three components. The first component is the concatenation of the initial of the first name of the driver with the initial of the last name of the driver. The second component is the year of issue of the licence. The third component is an arbitrary serial number. For example, the string representation of the licence number for a licence issued to Mark Smith in 1990 would have the form, MS-1990-10, where the 10 is a serial number that, with the initials and year, guarantees the uniqueness of the licence number as a whole.
You should use the java.util.Date class to represent dates. However, you must not use deprecated methods of the Date class. So, for example, in your test classes use java.util.Calendar to construct dates of birth and dates of issue of licences. You can assume default time zone and locale. (Note, there are now better classes available in the java.time package which was introduced in Java 1.8 but it will be good experience to work with classes
which are written less well).
So far I've got the following implementation for the LicenceNumber class:
import java.util.Calendar;
import java.util.Date;
public class LicenceNumber {
private String licenceNo;
public LicenceNumber(Name driverName, Date issueDate){
setLicenceNo(driverName, issueDate);
}
public String getLicenceNo() {
return licenceNo;
}
public void setLicenceNo(Name driverName, Date issueDate) {
String initials;
initials = driverName.getForename().substring(0, 1) + driverName.getSurname().substring(0,1);
System.out.println(initials);
int issueYear = issueDate.getYear(); //Deprecated
}
}
I want to be able to get only the year from issueDate, but the only way I can figure out how to do it, is by using the deprecated method, getYear(). This is obviously against the criteria, so can anyone shed some light on how to get the Year from a Date object without using deprecated methods?
Thanks ahead.
Try this
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
Here is fix
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.YEAR));
Substitute the new date with the date you are wanting to get the year from.
I can think of three ways to obtain the year from a Date object but avoiding the deprecated methods. Two of the approaches use other Objects (Calendar and SimpleDateFormat), and the third parses the .toString() of the Date object (and that method is not deprecated). The .toString() is potentially locale specific, and there could be issues with the approach in other locales, but I am going to assume (famous last words) that the year is always the only sequence of 4 digits. One could also understand the specific locale and use other parsing approaches. For example, standard US/English puts the year at the end (e.g., "Tue Mar 04 19:20:17 MST 2014"), one could use the .lastIndexOf(" ") on the .toString().
/**
* Obtains the year by converting the date .toString() and
* finding the year by a regular expression; works by assuming that
* no matter what the locale, only the year will have 4 digits
*/
public static String getYearByRegEx(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// match only a 4 digit year
Pattern yearPat = Pattern.compile("^.*([\\d]{4}).*$");
// convert the date to its String representation; could pass
// this directly, but I prefer the intermediary variable for
// potential debugging
String localDate = dte.toString();
// obtain a matcher, and then see if we have the expected value
Matcher match = yearPat.matcher(localDate);
if (match.matches() && match.groupCount() == 1) {
year = match.group(1);
}
return year;
}
/**
* Constructs a Calendar object, and then obtains the year
* by using the Calendar.get(...) method for the year.
*/
public static String getYearFromCalendar(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// get a Calendar
Calendar cal = Calendar.getInstance();
// set the Calendar to the specific date; the reason why
// Calendar is deprecated is this mutability
cal.setTime(dte);
// get the year using the .get method, and convert to a String
year = String.valueOf(cal.get(Calendar.YEAR));
return year;
}
/**
* Uses the SimpleDateFormat with a format for only a year.
*/
public static String getYearByFormatting(Date dte)
throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// set a format only for the year
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
// format the date; the result is the year
year = sdf.format(dte);
return year;
}
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
cal.set(2014,
Calendar.MARCH,
04);
Date dte = cal.getTime();
System.out.println("byRegex: "+ getYearByRegEx(dte));
System.out.println("from Calendar: "+ getYearFromCalendar(dte));
System.out.println("from format: " + getYearByFormatting(dte));
}
All three approaches return the expected output based upon the test input.
Take a look at https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html and related classes. That can yield a string with just the "year" field from a given 'Date'.

Splitting a string into different array indexes Java?

I am trying to split a string into different array indexes. This string is coming from user input (through java.util.Scanner) and is being loaded into a String variable. How can I split the input from the string into different array indexes?
Also, how can I do the math functions that are implied by DOBbeing an int?
Here is my code:
import java.util.Scanner;
public class main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter date of birth (MM/DD/YYYY):");
String DOB;
DOB = input.next();
int age = 0;
age = 2013 - DOB - 1;
int age2 = 0;
age2 = age + 1;
System.out.println("You are " + age + " or " + age2 + " years old");
}
}
String[] parts = DOB.split("/");
int months = Integer.parseInt(parts[0]);
int days = Integer.parseInt(parts[1]);
int years = Integer.parseInt(parts[2]);
Then just use years instead of DOB in your calculations.
Better yet, use new Calendar() to get today's precise date, and compare against that.
Use DateTimeFormat as shown in Parse Date String to Some Java Object to parse your string into a DateTime object, and then access the members.
DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dateTime = format.parseDateTime(DOB);
This uses Joda Time library.
Alternatively you can use SimpleDateFormat in a similar manner, to parse it into a Date object.
I notice you're using keyboard input to recognize the string. If the user doesn't input what you expect it will crash your program. (If you're just starting Java, this is fine; you can just run it again)
You can make it easier to split by asking them thrice too eg:
int dob[] = new Integer[3]; // integer array made from Integer class-wrapper
System.out.println("Input day");
dob[0] = Integer.parseInt(input.next());
System.out.println("Input month");
dob[1] = Integer.parseInt(input.next());
System.out.println("Input year");
dob[2] = Integer.parseInt(input.next());
You now have three integers in an array, split and ready to manipulate.
If Integer can't parse the text input as a number you'll get a NumberFormatException.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class main {
public static void main(String args[]) {
// Man you should look onto doing your
// homework by yourself, ijs.
// But here it goes, hope i make myself clear.
Scanner input = new Scanner(System.in);
System.out.println("Enter date of birth (MM/DD/YYYY):");
String DOB;
DOB = input.next();
//
int age;
// You need to know when it is today. Its not 2013 forever.
java.util.Calendar cal = java.util.Calendar.getInstance();
// ^ The above gets a new Calendar object containing system time/date;
int cur_year = cal.get(Calendar.YEAR);
int cur_month = cal.get(Calendar.MONTH)+1; // 0-indexed field.
// Cool we need this info. ill skip the day in month stuff,
// you do that by your own, okay?
SimpleDateFormat dfmt = new SimpleDateFormat("MM/dd/yyyy");
int bir_year;
int bir_month;
try {
// If you wanna program, you must know that not all functions
// will exit as it's intended. Errors happen and YOU should deal with it.
// not the user, not the environment. YOU.
Date d = dfmt.parse(DOB); // This throws a parse exception.
Calendar c = Calendar.getInstance();
c.setTime(d);
bir_year = c.get(Calendar.YEAR);
bir_month = c.get(Calendar.MONTH)+1; // 0-indexed field;
age = cur_year - bir_year;
// Well, you cant be a programmer if you dont think on the logics.
if(cur_month < bir_month ) {
age -= 1;
// If the current month is not yet your birth month or above...
// means your birthday didnt happen yet in this year.
// so you still have the age of the last year.
}
// If code reaches this point, no exceptions were thrown.
// and so the code below wont execute.
// And we have the variable age well defined in memory.
} catch(ParseException e) {
// But if the date entered by the user is invalid...
System.out.println("The date you typed is broken bro.");
System.out.println("Type a date in the correct format MM/DD/YYYY and retry.");
return; // Got errors? tell the program to quit the function.
}
// Well now we can say to the user how old he is.
// As if he/she didnt know it ^^'
System.out.println(String.format("You are %d years old", age));
// **Not tested.
}
}

Categories

Resources