converting between 12 hour time format to military time - java

I am currently trying to write a method that takes a string like "1pm" and converts it to military time --> 13
Right now I have the following and it is not working correctly. Any tips would be greatly appreciated.
/**
* Set the hour of this appointment, using a more human-friendly
* string.
* #param newHour The new hour for this appointment, using an
* am/pm designation such as "9am" or "5pm".
*/
public void setTime(String newHour)
{
String day = newHour.substring(newHour.length() - 2);
String dig = newHour.substring(2, newHour.length() - 2);
if (dig.equals("12"))
{
dig = "0";
}
if (day.equals("am"))
{
hour = Integer.parseInt(dig);
}
else
{
hour = Integer.parseInt(dig) + 12;
}
}

Your "dig" string is wrong. Its startindex should be 0.
String dig = newHour.substring(0, newHour.length() - 2);

Related

how to find my current time lies between today's time and tommorow's time in JAVA [duplicate]

This question already has answers here:
Check if a given time lies between two times regardless of date
(32 answers)
Closed 3 years ago.
I'm trying to determine if the current time e.g. 19:30:00 is between 19:00:00 & 03:00:00 next day, but my code is failing.
my code fails with this condition
can i use date to campare time if yes please let me know how
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class DateUtils {
// format 24hre ex. 12:12 , 17:15
private static String HOUR_FORMAT = "HH:mm";
private DateUtils() { }
public static String getCurrentHour() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdfHour = new SimpleDateFormat(HOUR_FORMAT);
String hour = sdfHour.format(cal.getTime());
return hour;
}
/**
* #param target hour to check
* #param start interval start
* #param end interval end
* #return true true if the given hour is between
*/
public static boolean isHourInInterval(String target, String start, String end) {
return ((target.compareTo(start) >= 0)
&& (target.compareTo(end) <= 0));
}
/**
* #param start interval start
* #param end interval end
* #return true true if the current hour is between
*/
public static boolean isNowInInterval(String start, String end) {
return DateUtils.isHourInInterval
(DateUtils.getCurrentHour(), start, end);
}
// TEST
public static void main (String[] args) {
String now = DateUtils.getCurrentHour();
String start = "14:00";
String end = "14:26";
System. out.println(now + " between " + start + "-" + end + "?");
System. out.println(DateUtils.isHourInInterval(now,start,end));
/*
* output example :
* 21:01 between 14:00-14:26?
* false
*
*/
}
}
java.time.LocalTime is your friend here. Below is a quick example, sure it can be done somewhat shorter.
void test(){
var tz = ZoneId.of("CET");
var anyDate = LocalDate.of(2019,12,4);
var x = ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(18,59)),tz).toInstant();
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(18,59)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(19,01)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(00,00)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(02,59)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(03,01)),tz).toInstant(),tz)));
}
boolean testTime(Clock clock){
var evening =LocalTime.of(19,00);
var midnight =LocalTime.of(00,00);
var night =LocalTime.of(03,00);
LocalTime wallTime = LocalTime.now(clock);
return (wallTime.isAfter(evening) && wallTime.isBefore(midnight.minusNanos(1))) || (midnight.isBefore(wallTime) && wallTime.isBefore(night)) || wallTime.equals(midnight);
}

Calendar Instance return 1970 as year

i have writen a Method to calculate the difference between two Dates.
here is the Method:
/**
* Method to calculate time Difference between to Times Strings
*
* #param time1 The Current Time Time
* #param time2 Item Start Time
* #param item the Item should to be played
* #return Difference between Two Times as Seconds
*/
public static long timeDifference(String time1, String time2, Item item) {
// get the current Calendar Instance
Calendar now = Calendar.getInstance();
// calculate the days Difference between the Item Start Day and the current Day
int daysToAdd=0;
if(RestOperations.dayoffWeek<item.getDay()){
daysToAdd= (RestOperations.dayoffWeek-item.getDay()) * (-1);
}
else{
daysToAdd = 7-(RestOperations.dayoffWeek-item.getDay());
}
// parse the passed Times Strings to Date Objects
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(time1);
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
// set the Current Time to the current Calendar instance
now.setTime(date1);
// create Date for the Item
Calendar itemDate = Calendar.getInstance();
// set the Item Start Time to the Item Calendar Instance
itemDate.setTime(date2);
// add the Days Difference to the Item Calendar Insatnce to determinate the Start Date of the Item
itemDate.add(Calendar.DAY_OF_MONTH, daysToAdd);
// get Difference between the both Calendar Instances to determinate how much Seconds must the Thread be stopped
long difference = itemDate.getTimeInMillis()-now.getTimeInMillis();
/* if (date1 != null & date2 != null) {
difference = (int) (date2.getTime() - date1.getTime());
}*/
// start for debugging!
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
int hour2 = itemDate.get(Calendar.HOUR_OF_DAY);
int minute2 = itemDate.get(Calendar.MINUTE);
int sec2 = itemDate.get(Calendar.SECOND);
String currDate = now.get(Calendar.YEAR)+"-"+now.get(Calendar.MONTH)+"-"+now.get(Calendar.DAY_OF_MONTH)+" "+hour + ":" + minute + ":" + sec;
String itDate = itemDate.get(Calendar.YEAR)+"-"+itemDate.get(Calendar.MONTH)+"-"+itemDate.get(Calendar.DAY_OF_MONTH)+" "+hour2 + ":" + minute2 + ":" + sec2;
Log.i("CurDate: ", currDate);
Log.i("ItemStartDate: ", itDate);
Log.i("difff: ", difference+"");
// end of debugging
return difference;
}
When i run this Method for this example:
duration = Utility.timeDifference("11:8:56","07:04:43",6);
i got the year = 1970, The Month = 0 and the Duration is negative (<0)
So for explanation the first Parameter corresponds to the current Time. The second Parameter corresponds when the Item should start to Play and the third Parameter corresponds the Day of Week when the Item should start to Play.
At the above code i try to do the following:
The first Parameter should be transformed to the current Date: 20-11-2015 11:08:56.
The Second Parameter should be transformed using the third Parameter to the current Date: 21-11-2015 07:04:43.
can someone tell me please where could be the Error?

Why is there an error saying "symbol not found" when I clearly defined the Clock instances above? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public class TestClock {
public static void main(String[] args){
/*(1)declare int variables hA, mA, hB, mB, hC, mC
*/
int hA;
int mA;
int hB;
int mB;
int hC;
int mC;
/*(2)declare String variables milA, milB, milC, civA, civB, civC
*/
String milA;
String milB;
String milC;
String civA;
String civB;
String civC;
/*(3)declare Clock variables clockA, clockB, clockC */
Clock clockA;
Clock clockB;
Clock clockC;
/*(4)construct clockA using default constructor */
clockA = new Clock();
/*(5)construct clockB using alternate constructor
* for military time 2400
*/
clockB = new Clock();
/*(6)construct clockC using alternate constructor
* with hours=11 and minutes=45
*/
clockC = new Clock();
/*(7)print clockA, clockB, clockC on separate lines
*/
System.out.println(clockA());
System.out.println(clockB());
System.out.println(clockC());
EDIT: further instructions...
/*(8)assign hours and minutes to hA,mA, hB,mB, hC,mC
* using the hours() and minutes() methods
* for clockA, clockB, and clockC respectively
*/
hA = clockA(hours);
mA = clockA(minutes);
hB = clockB(hours);
mB = clockB(minutes);
hC = clockC(hours);
mC = clockC(minutes);
/*(9)assign militaryTime and civilianTime to milA, civA,
* milB, civB, milC, civC for clockA,clockB,clockC resp
* using the appropriate methods
*/
This program (TestClock) is made to test all the methods from the program Clock (made separately, see code below). The comments are the instructions for what we have to do. So why, for the print statements, does it say clockA, clockB, and clockC not found when I clearly have them defined above as new Clocks?
Here is the separate Clock program:
public class Clock {
/* instance field:
* totalMinutes is always between 1 and 24*60
*/
private int totalMinutes;
/** default constructor sets the clock to represent 12:01 a.m.
*/
public Clock(){
totalMinutes = 1;
} //end default constructor
/** alternate contructor sets clock to represent time in military
* parameter hours - number of hours since midnight previous day
* parameter minutes - number of minutes since last hour changed
* e.g. 14:03 military is equivalent to 2:03 p.m. civilian
* preconditions: 0<=hours<=24, 0<=minutes<=59,
* 0<hours*60 + minutes<=24*60
*/
public Clock(int hours, int minutes){
totalMinutes = hours*60 + minutes;
String errMsg = null;
if ( minutes < 0 || minutes > 59){
errMsg = "\nminutes="+minutes+" not between 0 and 59";
} else if ( hours < 0 || hours > 24){
errMsg = "\nhours="+hours + " not between 0 and 24";
} else if (totalMinutes < 1 || totalMinutes>60*24 ) {
errMsg = "\ntotalMinutes not between 1 and 24*60";
}
if (errMsg != null){
throw new IllegalArgumentException(errMsg);
}
} //end alternate constructor
/** returns the number of hours in this Clock's time
*/
public int hours(){
int hrs = totalMinutes / 60;
return hrs;
}
/** returns the number of minutes since the last hour change
*/
public int minutes(){
int min = totalMinutes % 60;
return min;
}
/** returns a printable version of the time in Military context
*/
public String militaryTime(){
String mTime = "",hStr="",mStr="";
int hours = totalMinutes / 60;
int minutes = totalMinutes % 60;
if (hours<10){
hStr = "0"+hours;
} else {
hStr = "" + hours;
}
if (minutes<10){
mStr = "0"+minutes;
} else {
mStr = "" + minutes;
}
mTime = hStr + "" + mStr;
return mTime;
}
/** returns a printable version of the time in Civilian context
*/
public String civilianTime(){
String cTime = "", mStr="", suffix="";
int hours = totalMinutes / 60;
int minutes = totalMinutes % 60;
if ( totalMinutes == 12*60 ){
cTime = "12:00 noon";
}else if ( totalMinutes == 24*60)
cTime = "12:00 midnight";
else { //neither noon nor midnight
if (minutes < 10) {
mStr = "0" + minutes;
} else {
mStr = "" + minutes;
}
if (totalMinutes > 12*60){
hours = hours - 12;
suffix = " p.m.";
} else {
suffix = " a.m.";
}
cTime = hours + ":" + mStr + suffix;
} //end neithernoon nor midnight
return cTime;
}
}
There is nothing like System.out.println(clockA()); i.e clockA().
Change it to System.out.println(clockA);. Override toString() in Clock class.
Why is there an error saying “symbol not found” when I clearly defined the Clock instances above?
Above error generally comes when the Class type is not recognized. So import your class Clock.
/*(7)print clockA, clockB, clockC on separate lines
*/
System.out.println(clockA());
System.out.println(clockB());
System.out.println(clockC());
you are using clockC() since you added () it refer to a method.
if you want to print your variable, use :
/*(7)print clockA, clockB, clockC on separate lines
*/
System.out.println(clockA);
System.out.println(clockB);
System.out.println(clockC);
The lines such as:
System.out.println(clockA());
hA = clockA(hours);
are wrong. clockA is an object and it is not a function to be called so don't use clockA().Similarly,clockA(hours) is wrong.clockA is not a method to be invoked with passing of argument i.e. "hours". Instead do proper invoking of methods through the object of class as :
int hA= clockA.hours();
and pass the parameters while creation of different objects of class Clock.
The parameterized constructor will be called as below:
clockA=new Clock(hours,minutes);
The non-parameterized constructor will be called as below:
clockA=new Clock();
Similarly pass different parameters for different objects created.

Parsing user time input in Java/GWT

What is the best way to parse time that a user typed in a text field in GWT? Default time formats require users to enter time exactly as the time format for locale specifies it.
I want to be more flexible as there are many different ways users can enter time. For example, entries like "8", "8p", "8pm", "8.15pm", "13:15", "1315", "13.15" should be valid.
I ended up with my own method that I want to share. This method returns time in milliseconds, which can be displayed using any data formats for the selected locale.
Any suggestions to improve it are highly appreciated.
EDIT: Improved following suggestions in comments.
public static Long parseTime(String value) {
// ";" is a common typo - we are not punishing users for it
value = value.trim().toLowerCase().replace(";", ":");
RegExp time12 = RegExp.compile("^(1[012]|[1-9])([:.][0-5][0-9])?(\\s)?(a|p|am|pm)?$");
RegExp time24 = RegExp.compile("^(([01]?[0-9]|2[0-3])[:.]?([0-5][0-9])?)$");
if (time12.test(value) || time24.test(value)) {
String hours = "0", minutes = "0";
if (value.contains(":") || value.contains(".")) {
String[] values = value.split("[:.]");
hours = values[0];
minutes = values[1].substring(0, 2);
} else {
// Process strings like "8", "8p", "8pm", "2300"
if (value.contains("a")) {
hours = value.substring(0, value.indexOf("a")).trim();
} else if (value.contains("p")) {
hours = value.substring(0, value.indexOf("p")).trim();
} else if (value.length() < 3) {
hours = value;
} else {
hours = value.substring(0, value.length() - 2);
minutes = value.substring(value.length() - 2);
}
}
if (value.contains("a") && hours.equals("12")) {
// 12am is actually zero hours
hours = "0";
}
Long time = (Long.valueOf(hours) * 60 + Long.valueOf(minutes)) * 60 * 1000;
if (value.contains("p") && !hours.equals("12")) {
// "pm" adds 12 hours to the total, except for 12pm
time += 12 * 60 * 60 * 1000;
}
return time;
}
return null;
}

Convert Date in Millisecond to Today, Yesterday, Last 7 Days, Last 30 Days in Java

I have some documents and its created time is in milliseconds.
I need to separate them as Today, Yesterday, Last 7 Days, Last 30 Days, More than 30 Days.
I used the following code:convertSimpleDayFormat(1347022979786);
public static String convertSimpleDayFormat(Long val) {
long displayTime = System.currentTimeMillis() - val;
displayTime = displayTime/86400000;
String displayTimeVal = "";
if(displayTime <1)
{
displayTimeVal = "today";
}
else if(displayTime<2)
{
displayTimeVal = "yesterday";
}
else if(displayTime<7)
{
displayTimeVal = "last7days";
}
else if(displayTime<30)
{
displayTimeVal = "last30days";
}
else
{
displayTimeVal = "morethan30days";
}
return displayTimeVal;
}
I am subtracting the current time and passing the milliseconds and converting to one day.
But the issue I'm facing is, I couldn't calculate the exact time for the date in milliseconds.
I want to calculate for Today as: From Midnight 00:00 to Midnight 24:00. (Exactly for 24 hours.)
Similarly I want to exactly convert the Milliseconds into Today, Yesterday, Last 7 days, Last 30 Days and More than 30 Days.
private static Calendar clearTimes(Calendar c) {
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
return c;
}
public static String convertSimpleDayFormat(long val) {
Calendar today=Calendar.getInstance();
today=clearTimes(today);
Calendar yesterday=Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_YEAR,-1);
yesterday=clearTimes(yesterday);
Calendar last7days=Calendar.getInstance();
last7days.add(Calendar.DAY_OF_YEAR,-7);
last7days=clearTimes(last7days);
Calendar last30days=Calendar.getInstance();
last30days.add(Calendar.DAY_OF_YEAR,-30);
last30days=clearTimes(last30days);
if(val >today.getTimeInMillis())
{
return "today";
}
else if(val>yesterday.getTimeInMillis())
{
return "yesterday";
}
else if(val>last7days.getTimeInMillis())
{
return "last7days";
}
else if(val>last30days.getTimeInMillis())
{
return "last30days";
}
else
{
return "morethan30days";
}
}
It's a small hack, not severely tested. Use at own risk. I've made it extensible so you can add new durations.
public static String prettyTimeStamp(long timeStamp) {
Calendar c = Calendar.getInstance();
c.clear(Calendar.HOUR_OF_DAY);
c.clear(Calendar.MINUTE);
c.clear(Calendar.SECOND);
c.clear(Calendar.MILLISECOND);
long today = c.getTimeInMillis();
final long oneDay = 24 * 60 * 60 * 1000L;
final long[] durations = new long[] { today - oneDay, today,
today + 7 * oneDay, today + 30 * oneDay };
final String[] labels = "Yesterday,Today,Last 7 days,Last 30 Days,More than 30 Days"
.split(",");
int pos = Arrays.binarySearch(durations, timeStamp);
return labels[pos < 0 ? ~pos : pos];
}
By the way, you should really just use a Library like PrettyTime

Categories

Resources