Read the hour and minute from a time string [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
There is one problem String has ":"
String time = "21:45";
How does convert this string to two int:
int hour = 21;
int minute = 45;

Straight forward, non-validating way:
String[] parts = time.split(":");
int hour = Integer.parseInt(parts[0]);
int minute = Integer.parseInt(parts[1]);

You should consider using Calendar to parse such time strings:
String time = "21:45";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setLenient(false);
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(time));
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
System.out.println(hour);
System.out.println(minute);
21
45
You can handle the potential ParseException to deal with invalid inputs.

Here a truely validating solution:
String time = "21:45";
boolean valid = true;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setLenient(false); // important for validation
GregorianCalendar gcal = new GregorianCalendar();
try {
gcal.setTime(sdf.parse(time));
} catch (ParseException pe) {
valid = false;
}
if (valid) {
int hours = gcal.get(Calendar.HOUR_OF_DAY);
int minutes = gcal.get(Calendar.MINUTE);
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
} else {
System.out.println("Sorry, the input is not valid: " + time);
}

Try this:
String arr[]= time.split(":", 2);
int num1 = Integer.parseInt(arr[0]);
int num2 = Integer.parseInt(arr[1]);

Related

Time comparision in java

I just get the time in HH:MM format and check if it is greater than 9:30 then count c is increased as 1.I just did for a single user input time.But i need to get multiple times from user and compare.If it is greater than 9:30 then increment the count values.First get n value and then get n no of time from user.How can i change my code to get the n no of time and compare that?
Scanner input = new Scanner(System.in);
String time = input.nextLine();
System.out.println();
int c=0;
String time2 = "9:30";
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date d1 = sdf.parse(time);
Date d2 = sdf.parse(time2);
if(d1.after(d2))
{
c++;
}
System.out.println(c);
This should do it. It is a basic implementation, you can optimize it the way you like.
EDIT (with explanation comments):
Scanner sc = new Scanner(System.in);
// accept user input for N
System.out.println("Enter N");
int n = sc.nextInt();
String time;
int c = 0;
// store the DateFormat to compare the user inputs with
String time2 = "9:30";
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date d2 = null;
try {
d2 = sdf.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
// iterate for N times, asking for a user input N times.
for (int i = 0; i < n; i++) {
// get user's input to parse and compare
System.out.println("Enter Time");
time = sc.next();
Date d1 = null;
try {
d1 = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
if (d1.after(d2)) {
c++;
}
}
System.out.println(c);
I have not changed much of your code, just added a loop and did the same thing for N times. To quote from the comments above, "loops are your friend".
Hope this helps. Good luck. Comment if you have any further questions.
Use for loop to iterate over the list of time. Also, you do not need n value, you can directly get it with list.size()
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

How to get last three months first date and last date based on current date including current date in java?

I want to categorize values based on months so to filter those values required 1st & last date of last three months based on current month including current month values. Here how many last months is parameter. I wanted list of all months 1st date and last date. Any logic for the same will be helpful.
for example:-
// parameters
int lastMonths = 3;
date currentDate= 26-04-2019;
//expected output
current month is 04-2019 ,1st date is 1-04-2019 and last date is 30-04-2019
previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019
Use java.util.Calendar for addition and subraction in date
and
java.text.DateFormat to format date
DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
DateFormat monthFormat = new SimpleDateFormat("MM-yyyy", Locale.US);
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse("26-04-2019"));
for (int i = 0; i < 3; i++){
System.out.println("currentDate: " + monthFormat.format(cal.getTime())); // print current month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("first date: " + format.format(cal.getTime())); // print first date
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
System.out.println("last date: " + format.format(cal.getTime())); // print last date
cal.add(Calendar.MONTH, -1);
}
Important to say - there are tons of libraries who will give you this specific need, but I would like relying on one that does the work and was actually designed for (some of yours...) those use cases -
Java.time.LocalDate library (already built into Java 8)
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2019-04-26
In order to get first and last days of month, you can use:
LocalDate start = YearMonth.now().atDay(1);
(now can be some other month, of course)
LocalDate end = YearMonth.now().atEndOfMonth();
You can use it specifically on one / two months, or with some for loop. Examples below:
1. Specific call:
LocalDate earlierOneMonth = now.minusMonths(1); // 2019-03-26
earlierOneMonth.getDay(); // 26
2. For Loop: (so you'll need something like an array / list to store those values...)
for(int i=0; i < lastMonths - 1; i++){
arr(i) = now.minusMonths(i + 1);
}
Also, in order to get the name of the month, you can use ->
earlierOneMonth.getMonth(); // APRIL
earlierOneMonth.getMonth.getValue(); // 04
Lastly, in order to get the year, you can use ->
earlier.getYear(); // 2019
Once you have all of your desired values, you can print them out as you requested, with that expected output:
"current month is" + nowMonth + "-" + nowYear + " ,1st date is" + nowDay + "-" + nowMonth + "-" + nowYear + " and last date is ...
Let me know if it's clear enough :)
tl;dr
YearMonth.now().minusMonths( 3 ).atDay( 1 ) // Get the first day of the month of three months ago. Returns `LocalDate` object.
YearMonth.now().minusMonths( 3 ).atEndOfMonth() // Get the last day of the month of three months ago. Returns `LocalDate` object.
YearMonth
You really care about the months. The dates are secondary. So focus on the months. Java has a class for that!
The YearMonth class represents a particular month of a particular year.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
YearMonth currentYm = YearMonth.now( z ) ;
Collect your months of interest.
List< YearMonth > yms = new ArrayList<>() ;
int limit = 3 ; // We want current month plus three previous months.
for( int i = 0 ; i <= limit ; i ++ ) {
YearMonth ym = currentYm.minusMonths( i ) ;
yms.add( ym ) ;
}
When you need dates, loop the list. Let YearMonth determine the first and last days of the month.
for( YearMonth ym : yms ) {
System.out.println( "YearMonth: " + ym + " starts: " + ym.atDay( 1 ) + " ends: " + ym.atEndOfMonth() ) ;
}
See this code run live at IdeOne.com.
YearMonth: 2019-04 starts: 2019-04-01 ends: 2019-04-30
YearMonth: 2019-03 starts: 2019-03-01 ends: 2019-03-31
YearMonth: 2019-02 starts: 2019-02-01 ends: 2019-02-28
YearMonth: 2019-01 starts: 2019-01-01 ends: 2019-01-31
If you need a Date object then the following will do just fine
Date date = getDate(targetDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, -3);
calendar.set(Calendar.DAY_OF_MONTH, 1);
// calendar.getTime()
// The line above returns Date object
If you need a plain String then you can format it any way you want by simply using DateTimeFormatter from org.joda.time library and just use it's print() method on calendar.getTimeInMillis().
LocalDate currentDate = LocalDate.of(2019, 4, 26);//current date
System.out.println(currentDate);
int lastMonths = 3;//number of months
LocalDate prevDate = null;
LocalDate start = null;
LocalDate end = null;
for(int i = 0; i < lastMonths; i++) {
if(prevDate == null) {
start = currentDate.withDayOfMonth(1);//First day of current month
end = currentDate.withDayOfMonth(currentDate.lengthOfMonth());//Last day of current month
prevDate = currentDate.minusMonths(1);//subtracting one month from current month
} else {
start = prevDate.withDayOfMonth(1);//First day of previous month
end = prevDate.withDayOfMonth(prevDate.lengthOfMonth());//Last day of previous month
prevDate = prevDate.minusMonths(1);//subtracting one month from previous month
}
System.out.println(start + " " + end);
}
Output:
2019-04-26
2019-04-01 2019-04-30
2019-03-01 2019-03-31
2019-02-01 2019-02-28
Reference:
Get first and last day of month using threeten, LocalDate
int lastMonths = 3;
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
DateFormat monthYearFormat = new SimpleDateFormat("MM-yyyy");
for (int i = 0; i < lastMonths; i++) {
int monthOfYear = month - i;
// if month is january, reset couter and month
if(monthOfYear == 0) {
month = 13;
year -= 1;
i = 0;
continue;
}
// get last day of month (month length)
YearMonth yearMonth = YearMonth.of(year, monthOfYear);
int firstDay = 1;
int lastDay = yearMonth.lengthOfMonth();
// create date with given year, month and day
Date date = new GregorianCalendar(year, monthOfYear - 1, firstDay).getTime();
String monthAndYear = monthYearFormat.format(date);
String currentOrPrevious;
if (i == 0) {
currentOrPrevious = "current";
} else {
currentOrPrevious = "previous";
}
String output = String.format("%s month is %s, 1st date is %02d-%s and last date is %d-%s", currentOrPrevious, monthAndYear, firstDay, monthAndYear, lastDay, monthAndYear);
System.out.println(output);
}
Output:
current month is 04-2019, 1st date is 01-04-2019 and last date is 30-04-2019
previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019

create a calendar of any year in ms word file using java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create calendar of any year in ms word file using java.could you please help me out.thanks in advance.
Following is the code to write calender for particular year in docx file
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Scanner;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class MyCalendar {
//Blank Document
static XWPFDocument document= new XWPFDocument();
public static void main(String[] args) {
// represents the year
int year;
// ask year from user
Scanner in = new Scanner(System.in);
System.out.print("Enter year: ");
// read them as string
String yearText = in.next();
in.close();
try {
//Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("Year "+yearText+".docx"));
// throws NumberFormatException if not convertible.
// It would be caught below:
year = Integer.parseInt(yearText);
// print the calendar for the given year.
for(int i=1; i<=12; i++){
printCalendarMonthYear(i, year);
}
document.write(out);
out.close();
} catch (NumberFormatException e) {
// handles NumberFormatException
System.err.println("Numberat Error: " + e.getMessage());
} catch (Exception e) {
// handles any other Exception
System.err.println(e.getMessage());
}
}
/*
* prints a calendar month based on month / year info
*/
private static void printCalendarMonthYear(int month, int year) {
// create a new GregorianCalendar object
Calendar cal = new GregorianCalendar();
// set its date to the first day of the month/year given by user
cal.clear();
cal.set(year, month - 1, 1);
document.createParagraph().createRun().setText(""+cal.getDisplayName(Calendar.MONTH, Calendar.LONG,
Locale.US) + " " + cal.get(Calendar.YEAR));
// obtain the weekday of the first day of month.
int firstWeekdayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
// obtain the number of days in month.
int numberOfMonthDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
// print anonymous calendar month based on the weekday of the first
// day of the month and the number of days in month:
printCalendar(numberOfMonthDays, firstWeekdayOfMonth-1);
}
/*
* prints an anonymous calendar month based on the weekday of the first
* day of the month and the number of days in month:
*/
private static void printCalendar(int numberOfMonthDays, int firstWeekdayOfMonth) {
// reset index of weekday
int weekdayIndex = 0;
// print calendar weekday header
XWPFTable table = document.createTable();
//create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("Su");
tableRowOne.addNewTableCell().setText("Mo");
tableRowOne.addNewTableCell().setText("Tu");
tableRowOne.addNewTableCell().setText("We");
tableRowOne.addNewTableCell().setText("Th");
tableRowOne.addNewTableCell().setText("Fr");
tableRowOne.addNewTableCell().setText("Sa");
// leave/skip weekdays before the first day of month
XWPFTableRow tableRow = table.createRow();
int ind = 0;
for (int day = 1; day <= firstWeekdayOfMonth; day++) {
ind = day;
tableRow.getCell(ind).setText(" ");
weekdayIndex++;
}
// print the days of month in tabular format.
for (int day = 1; day <= numberOfMonthDays; day++) {
// print day
tableRow.getCell(ind).setText(""+day);
// next weekday
weekdayIndex++;
// if it is the last weekday
if (weekdayIndex == 7) {
// reset it
weekdayIndex = 0;
// and go to next line
tableRow = table.createRow();
ind = 0;
}
else { // otherwise
// print space
ind++;
}
}
// print a final new-line.
document.createParagraph().createRun().addBreak();
}
}
This will create docx file with year name
You will need following jar files to run this code
poi-3.11.jar
poi-ooxml-3.11.jar
poi-ooxml-schemas-3.11.jar
xmlbeans-2.6.jar

Java code to determine number of days elapsed does not return correct answer

The problem with this code is that it does calculate the days alive only for some birth dates. I tried using different birth dates and testing it with an online calculator and it seems not all are correct. I think the problem is because of Leapyears, more and less than 30 days in a month.
public class DaysAlive {
public static void main (String [] args){
Scanner userInput = new Scanner(System.in);
int TodayYear, TodayMonth, TodayDay;
int YearBorn, MonthBorn, DayBorn;
int DaysAlive;
System.out.println("Enter today's date");
System.out.print ("Year: ");
TodayYear = userInput.nextInt ();
System.out.print ("Month: ");
TodayMonth = userInput.nextInt ();
System.out.print ("Day: ");
TodayDay = userInput.nextInt ();
System.out.println("Enter date of birth");
System.out.print ("Year: ");
YearBorn = userInput.nextInt ();
System.out.print ("Month: ");
MonthBorn = userInput.nextInt ();
System.out.print ("Day: ");
DayBorn = userInput.nextInt ();
//I think this line is the problem
DaysAlive = (TodayYear - YearBorn) *365 + (TodayMonth - MonthBorn) *30 +(TodayDay - DayBorn);
System.out.println("DaysAlive: " + DaysAlive);
}
}
How about using Calendar? It will do all of that for you... or joda time library
check it out here:
Getting the number of days between two dates in java
If I understand what you want, you should be able to use something like this -
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter today's date");
System.out.print("Year: ");
int todayYear = userInput.nextInt();
System.out.print("Month: ");
int todayMonth = userInput.nextInt();
System.out.print("Day: ");
int todayDay = userInput.nextInt();
// Java has January as month 0. Let's not require that the user know.
Calendar today = new GregorianCalendar(todayYear, todayMonth - 1,
todayDay);
System.out.println("Enter date of birth");
System.out.print("Year: ");
int yearBorn = userInput.nextInt();
System.out.print("Month: ");
int monthBorn = userInput.nextInt();
System.out.print("Day: ");
int dayBorn = userInput.nextInt();
Calendar born = new GregorianCalendar(yearBorn, monthBorn - 1, dayBorn);
double diff = today.getTimeInMillis() - born.getTimeInMillis();
diff = diff / (24 * 60 * 60 * 1000); // hours in a day, minutes in a hour,
// seconds in a minute, millis in a
// second.
System.out.println(Math.round(diff));
}
With output
Enter today's date
Year: 2014
Month: 03
Day: 14
Enter date of birth
Year: 2014
Month: 03
Day: 13
1
You are right, the problem is that not all months have 30 days in them. A simple solution would to be use if statements and make another integer variable called something like monthMultiplier. As other people pointed out you can also use the Calendar
if(TodayMonth == 9 || TodayMonth == 11 || TodayMonth == 4 || TodayMonth == 6) {
monthMultiplier = 30;//30 days in these months
}
if(TodayMonth == 2){
monthMultiplier = 28;//WELL 28.25 accounting for leap years
}
else {
monthMultiplier = 31;
}
DaysAlive = (TodayYear - YearBorn) *365 + (TodayMonth - MonthBorn) * monthMultiplier +(TodayDay - DayBorn);
Joda-Time
The Joda-Time library makes easy work of this problem. Just one line of code, basically. Joda-Time handles time zones, leap days, and other issues.
Hand-coding such date-time work is risky, error-prone, and frankly silly given the excellent libraries available (Joda-Time and the new java.time package in Java 8).
Example Code
Here’s some example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime start = new DateTime(2008, 4, 26, 0, 0, 0, timeZone);
DateTime stop = new DateTime(2008, 5, 26, 0, 0, 0, timeZone);
int daysBetween = Days.daysBetween( start, stop ).getDays();
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "daysBetween: " + daysBetween );
When executed…
start: 2008-04-26T00:00:00.000+02:00
stop: 2008-05-26T00:00:00.000+02:00
daysBetween: 30

Java class - add n hours, minutes, and seconds to a time

I am fairly new to Java would like to know if this logic looks sound. The purpose of this class is to receive input from the user for a time in 12-hour format. Then the user is prompted to input a period of time. Finally, it outputs the final time (with the time added), in 12-hour format. I've run several tests scenarios through this and everything seems to be working fine. I'd just like some additional sets of trained eyes to look at it before I call it good. Thanks for your help!
import javax.swing.JOptionPane;
public class M3E7 {
public static void main(String args[]) {
String start_hr = null;
String start_min = null;
String start_sec = null;
String abbr = null;
String hr = null;
String min = null;
String sec = null;
int start_hr_num = 0;
int start_min_num = 0;
int start_sec_num = 0;
int hr_num = 0;
int min_num = 0;
int sec_num = 0;
int final_hr = 0;
int final_min = 0;
int final_sec = 0;
start_hr = JOptionPane.showInputDialog("Start time - Enter the hours.");
start_min = JOptionPane.showInputDialog("Start time - Enter the minutes.");
start_sec = JOptionPane.showInputDialog("Start time - Enter the seconds.");
abbr = JOptionPane.showInputDialog("Start time - Enter either am or pm.");
hr = JOptionPane.showInputDialog("Enter the number of hours to add (less than 24).");
min = JOptionPane.showInputDialog("Enter the number of minutes to add (less than 60).");
sec = JOptionPane.showInputDialog("Enter the number of seconds to add (less than 60).");
start_hr_num = Integer.parseInt(start_hr);
start_min_num = Integer.parseInt(start_min);
start_sec_num = Integer.parseInt(start_sec);
hr_num = Integer.parseInt(hr);
min_num = Integer.parseInt(min);
sec_num = Integer.parseInt(sec);
if (abbr.equals("pm")); {
start_hr_num += 12;
}
final_hr = (start_hr_num + hr_num);
final_min = (start_min_num + min_num);
final_sec = (start_sec_num + sec_num);
if (final_sec >= 60) {
final_min++;
final_sec -= 60;
}
if (final_min >= 60) {
final_hr++;
final_min -= 60;
}
if (final_hr >= 24) {
final_hr -= 24;
}
if (final_hr > 12) {
final_hr -= 12;
abbr.equals("pm");
}
else if (final_hr == 12) {
final_hr -= 12;
abbr.equals("am");
}
else {
abbr.equals("am");
}
JOptionPane.showMessageDialog(null, "The new time of day is " + final_hr + ":" + final_min + ":" + final_sec + " " + abbr);
System.exit(0);
}
}
Do yourself a favour and don't perform date/time arithmetic yourself.
Instead, use Joda Time to handle it for you:
Parse the first input as a LocalTime (via DateTimeFormatter.parseLocalTime)
Parse the next three inputs as Period values using Period.hours(), Period.minutes() and Period.seconds()
Use LocalTime.plus(ReadablePeriod) to add the period to the time
Format and output as you wish
Since it is homework, I don't want to give you the entire answer written up, but at least give you something to think about.
All times and dates are stored as milliseconds from epoch (ie: jan 1, 1970). The way I would approach the problem is take the date that the user entered, and create a java.util.Date() object from it. From that Date object, you can simply add/subtract the number of milliseconds from the user's "period".
Then, it simply becomes an exercise to print out the new date object.
Of course, I don't know if this is already too complicated for your class or not, but it is a fairly simple approach (assuming that you have already used Date objects) without using any 3rd party libs (like Joda Time).
As #Jon Skeet mentioned, use Joda Time. It will help you do the complex date calculations easily.

Categories