convert time(12h and 24h) - java

I'm writing a program that converts the time (12h and 24h).
The result I want to get is the following:
convertTime ("12:00") ➞ "0:00"
convertTime ("6:20 pm") ➞ "18:20"
convertTime ("21:00") ➞ "9:00 pm"
convertTime ("5:05") ➞ "5:05"
this is my code, unfortunately the result is not what I expected, in fact:
A time input of 12 hours will be indicated with an am or pm suffix.
An input time of 24 hours contains no suffix.
I would appreciate a help so much, thanks in advance!
public static String convertTime(String time) {
String hour = time.substring(0, time.indexOf(":"));
String min = time.substring(3, time.indexOf(":") + 3);
int hourInteger = Integer.parseInt(hour);
if (hourInteger > 12 && hourInteger < 24) {
hourInteger = hourInteger - 12;
}
if (hourInteger == 24) {
hourInteger = 0;
}
if (hourInteger < 12) {
return hourInteger + ":" + min + " AM";
}
if (hourInteger > 12)
return hourInteger + ":" + min + " PM";
return hourInteger;
}

You can use below code snippet, you can make additional changes accordingly as your wish. Using Date API to parse vise versa 12 <-> 24 Hours format.
public static String convertTime(String time) throws ParseException {
if (time.contains("am") || time.contains("pm")) {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse(time);
return displayFormat.format(date);
} else {
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse(time);
return displayFormat.format(date);
}
}

There were few problems with your code.
One is return hourInteger. As the convertTime() return type is String, you can't return an Integer. To convert it you can use,
String.valueOf(hourInteger);
Second in 24h clock format, there is no 24:00. A minute after 23:59 is 00:00. So,
if (hourInteger == 24) {
should be,
if (hourInteger == 0) {
Third,
if (hourInteger > 12 && hourInteger < 24) {
hourInteger = hourInteger - 12;
}
above code will convert all possible hours larger than 12 to hours smaller than 12. So after that line checking if(hourInteger>12) always returns false.
Below code will work for your situation.
public static String convertTime(String time) {
String hour = time.substring(0, time.indexOf(":"));
String min = time.substring(3, time.indexOf(":") + 3);
int hourInteger = Integer.parseInt(hour);
int newHour = hourInteger;
if (hourInteger > 12 && hourInteger < 24) {
newHour = hourInteger - 12;
}
if (hourInteger==0) {
newHour = 12;
}
if (hourInteger < 12) {
return newHour + ":" + min + " AM";
}else {
return newHour + ":" + min + " PM";
}
}

You can use StringTokenizer to split the string into tokens using delimiters : and , then convert based on number of tokens (2 for 24 hour format, 3 for 12 hour format):
import java.util.*;
public class Main
{
public static String convertTime(String time) {
StringTokenizer sb = new StringTokenizer(time, ": ");
if (sb.countTokens() == 2)
{
// 24 hr to 12 hr
int hour = Integer.parseInt(sb.nextToken());
int min = Integer.parseInt(sb.nextToken());
boolean isEvening = false;
if (hour >= 12 && hour <= 24)
{
hour -= 12;
if (hour != 0)
isEvening = true;
}
return String.format("%02d:%02d %s", hour, min, (isEvening ? "pm" : "am"));
}
else if (sb.countTokens() == 3)
{
// 12 hr to 24 hr
int hour = Integer.parseInt(sb.nextToken());
int min = Integer.parseInt(sb.nextToken());
boolean isEvening = sb.nextToken().equalsIgnoreCase("pm");
if (isEvening || hour == 0)
{
hour += 12;
}
return String.format("%02d:%02d", hour, min);
}
return "";
}
public static void main(String[] args) {
System.out.println(convertTime("12:00"));
System.out.println(convertTime("6:20 pm"));
System.out.println(convertTime("21:00"));
System.out.println(convertTime("5:05"));
}
}

Related

Is their any simplified Java to find palindome dates between year 0000 and 9999?

import java.util.Arrays;
public class PalindromeDates {
static final int STARTINGYEAR = 0000;
static final int ENDINGYEAR = 9999;
public static void main(String[] args) {
int year, month, date;
int dateArray[];
boolean flag;
System.out.println(" Date --> Array Format\n");
for (year = STARTINGYEAR; year <= ENDINGYEAR; year++) {
for (month = 01; month <= 12; month++) {
for (date = 1; date <= 31; date++) {
if (checkValidDate(year, date, month)) {
dateArray = createDateArray(date, month, year);
flag = checkPalindrome(dateArray);
if (flag) {
System.out.print(year + "." + month + "." + date + " --> ");
System.out.println(Arrays.toString(dateArray));
}
}
}
}
}
}
public static int[] createDateArray(int date, int month, int year) { //Inserting the whole date to an array
int dateArray[] = new int[8];
dateArray[0] = year / 1000;
year = year % 1000;
dateArray[1] = year / 100;
year = year % 100;
dateArray[2] = year / 10;
dateArray[3] = year % 10;
dateArray[4] = month / 10;
dateArray[5] = month % 10;
dateArray[6] = date / 10;
dateArray[7] = date % 10;
return dateArray;
}
public static boolean checkPalindrome(int dateArray[]) {
for (int i = 0; i <= 3; i++) {
if (dateArray[i] == dateArray[7 - i]) {
} else {
return false;
}
}
return true;
}
public static boolean checkValidDate(int year, int month, int date) {
if (month == 2 && date == 30)
return false;
if ((month == 2 || month == 4 || month == 6 || month == 9 || month == 11) && (date == 31)) {
return false;
}
if ((month == 2) && (date == 29))
return (checkLeapYear(year));
return true;
}
public static boolean checkLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
return true;
else
return false;
} else
return true;
} else {
return false;
}
}
}
This program is written by me to find the palindrome dates since 0000 to 9999. Is their any simplifies program to do this?. What are the modifications for this code? And I want to know whether my leap year finding code is correct.
There is a method called createDateArray(). It is used to put the integer digits in year, month, date to an array. Is there any simple method to do that?
I am inferring from your code that a palindrome date is a date that formatted into yyyyMMdd format is a palindrome string. For example the day before yesterday, February 2, 2020, was a palindrome date because it’s formatted into 20200202, a palindrome.
Is their any simplifies program to do this? …
Yes there is. See below.
… And I want to know whether my leap year finding code is correct.
Yes, it is correct. I have tested its result against the result of Year.of(y).isLeap() for y ranging from 0 through 9999.
And the issue you didn’t ask about: as jrook hinted in a comment, beware of octal numbers.
static final int STARTINGYEAR = 0000;
While this works in this case, it works for reasons that I am afraid that you don’t fully understand. You will get surprises if some day you try 0500 for year 500 and get 320, or you use 0008 for year 8 and get a compile time error. When a Java integer literal begins with 0 (and has more digits following it), it is an octal number, not a number in the decimal number system. So in your code you should use 0 for the year that you want printed as 0000:
static final int STARTINGYEAR = 0;
java.time
On one side Andreas is correct in the other answer that this goes a lot more smoothly when using the date classes that are built into Java. On the other side the Calendar class used in that answer is poorly designed and long outdated. So I recommend we don’t use it and instead present a solution using java.time, the modern Java date and time API.
List<LocalDate> palindromeDates = Arrays.stream(Month.values())
.flatMap(m -> IntStream.rangeClosed(1, m.length(true)).mapToObj(d -> MonthDay.of(m, d)))
.map(md -> md.atYear(reverseStringToInt(md.format(monthDayFormatter))))
.sorted()
.collect(Collectors.toList());
palindromeDates.forEach(ld -> System.out.println(ld.format(dateFormatter)));
This code uses a few auxiliaries:
private static DateTimeFormatter monthDayFormatter = DateTimeFormatter.ofPattern("MMdd");
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
private static int reverseStringToInt(String s) {
StringBuilder buf = new StringBuilder(s);
buf.reverse();
return Integer.parseInt(buf.toString());
}
Excerpt from the output:
01011010
01100110
01111110
01200210
…
20111102
20200202
20211202
…
92800829
92900929
The algorithm idea is stolen from Andreas’ answer since it is so well thought.
Link
Oracle tutorial: Date Time explaining how to use java.time.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
for (LocalDate d = LocalDate.of(0, 1, 1); d.isBefore(LocalDate.of(10000, 1, 1)); d = d.plusDays(1)) {
String dateString = dateFormatter.format(d);
if (dateString.equals(new StringBuilder(dateString).reverse().toString())) {
System.out.println(d);
}
}
Since the year can be any 4-digit year, there is no constraint there, so just go through all 3661 MMdd values of a year, reverse it and use as the year.
1) Since the leap date of 0229 reversed is 9220, it is a leap year, and hence a valid palindrome date.
As code, using Calendar, in year order:
List<String> palimdromeDates = new ArrayList<>();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"/*No DST*/));
cal.clear();
cal.set(2000/*Leap Year*/, Calendar.JANUARY, 1);
for (; cal.get(Calendar.YEAR) == 2000; cal.add(Calendar.DAY_OF_YEAR, 1)) {
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) + 1;
int year = 0; // Calculate: year = reverse(MMdd)
for (int i = 0, n = month * 100 + day; i < 4; i++, n /= 10)
year = year * 10 + n % 10;
palimdromeDates.add(String.format("%04d-%02d-%02d", year, month, day));
}
Collections.sort(palimdromeDates); // Sort by year
for (String date : palimdromeDates)
System.out.println(date);
Note that this code only loops 366 times, and does not create any unnecessary String objects or other type of objects, so it is very fast, and generates minimum garbage.
Output
0101-10-10
0110-01-10
0111-11-10
0120-02-10
0121-12-10
0130-03-10
0140-04-10
0150-05-10
0160-06-10
0170-07-10
0180-08-10
0190-09-10
0201-10-20
0210-01-20
0211-11-20
0220-02-20
0221-12-20
0230-03-20
0240-04-20
0250-05-20
0260-06-20
0270-07-20
0280-08-20
0290-09-20
0301-10-30
0310-01-30
0311-11-30
0321-12-30
0330-03-30
0340-04-30
0350-05-30
0360-06-30
0370-07-30
0380-08-30
0390-09-30
1001-10-01
1010-01-01
1011-11-01
1020-02-01
1021-12-01
1030-03-01
1040-04-01
1050-05-01
1060-06-01
1070-07-01
1080-08-01
1090-09-01
1101-10-11
1110-01-11
1111-11-11
1120-02-11
1121-12-11
1130-03-11
1140-04-11
1150-05-11
1160-06-11
1170-07-11
1180-08-11
1190-09-11
1201-10-21
1210-01-21
1211-11-21
1220-02-21
1221-12-21
1230-03-21
1240-04-21
1250-05-21
1260-06-21
1270-07-21
1280-08-21
1290-09-21
1301-10-31
1310-01-31
1321-12-31
1330-03-31
1350-05-31
1370-07-31
1380-08-31
2001-10-02
2010-01-02
2011-11-02
2020-02-02
2021-12-02
2030-03-02
2040-04-02
2050-05-02
2060-06-02
2070-07-02
2080-08-02
2090-09-02
2101-10-12
2110-01-12
2111-11-12
2120-02-12
2121-12-12
2130-03-12
2140-04-12
2150-05-12
2160-06-12
2170-07-12
2180-08-12
2190-09-12
2201-10-22
2210-01-22
2211-11-22
2220-02-22
2221-12-22
2230-03-22
2240-04-22
2250-05-22
2260-06-22
2270-07-22
2280-08-22
2290-09-22
3001-10-03
3010-01-03
3011-11-03
3020-02-03
3021-12-03
3030-03-03
3040-04-03
3050-05-03
3060-06-03
3070-07-03
3080-08-03
3090-09-03
3101-10-13
3110-01-13
3111-11-13
3120-02-13
3121-12-13
3130-03-13
3140-04-13
3150-05-13
3160-06-13
3170-07-13
3180-08-13
3190-09-13
3201-10-23
3210-01-23
3211-11-23
3220-02-23
3221-12-23
3230-03-23
3240-04-23
3250-05-23
3260-06-23
3270-07-23
3280-08-23
3290-09-23
4001-10-04
4010-01-04
4011-11-04
4020-02-04
4021-12-04
4030-03-04
4040-04-04
4050-05-04
4060-06-04
4070-07-04
4080-08-04
4090-09-04
4101-10-14
4110-01-14
4111-11-14
4120-02-14
4121-12-14
4130-03-14
4140-04-14
4150-05-14
4160-06-14
4170-07-14
4180-08-14
4190-09-14
4201-10-24
4210-01-24
4211-11-24
4220-02-24
4221-12-24
4230-03-24
4240-04-24
4250-05-24
4260-06-24
4270-07-24
4280-08-24
4290-09-24
5001-10-05
5010-01-05
5011-11-05
5020-02-05
5021-12-05
5030-03-05
5040-04-05
5050-05-05
5060-06-05
5070-07-05
5080-08-05
5090-09-05
5101-10-15
5110-01-15
5111-11-15
5120-02-15
5121-12-15
5130-03-15
5140-04-15
5150-05-15
5160-06-15
5170-07-15
5180-08-15
5190-09-15
5201-10-25
5210-01-25
5211-11-25
5220-02-25
5221-12-25
5230-03-25
5240-04-25
5250-05-25
5260-06-25
5270-07-25
5280-08-25
5290-09-25
6001-10-06
6010-01-06
6011-11-06
6020-02-06
6021-12-06
6030-03-06
6040-04-06
6050-05-06
6060-06-06
6070-07-06
6080-08-06
6090-09-06
6101-10-16
6110-01-16
6111-11-16
6120-02-16
6121-12-16
6130-03-16
6140-04-16
6150-05-16
6160-06-16
6170-07-16
6180-08-16
6190-09-16
6201-10-26
6210-01-26
6211-11-26
6220-02-26
6221-12-26
6230-03-26
6240-04-26
6250-05-26
6260-06-26
6270-07-26
6280-08-26
6290-09-26
7001-10-07
7010-01-07
7011-11-07
7020-02-07
7021-12-07
7030-03-07
7040-04-07
7050-05-07
7060-06-07
7070-07-07
7080-08-07
7090-09-07
7101-10-17
7110-01-17
7111-11-17
7120-02-17
7121-12-17
7130-03-17
7140-04-17
7150-05-17
7160-06-17
7170-07-17
7180-08-17
7190-09-17
7201-10-27
7210-01-27
7211-11-27
7220-02-27
7221-12-27
7230-03-27
7240-04-27
7250-05-27
7260-06-27
7270-07-27
7280-08-27
7290-09-27
8001-10-08
8010-01-08
8011-11-08
8020-02-08
8021-12-08
8030-03-08
8040-04-08
8050-05-08
8060-06-08
8070-07-08
8080-08-08
8090-09-08
8101-10-18
8110-01-18
8111-11-18
8120-02-18
8121-12-18
8130-03-18
8140-04-18
8150-05-18
8160-06-18
8170-07-18
8180-08-18
8190-09-18
8201-10-28
8210-01-28
8211-11-28
8220-02-28
8221-12-28
8230-03-28
8240-04-28
8250-05-28
8260-06-28
8270-07-28
8280-08-28
8290-09-28
9001-10-09
9010-01-09
9011-11-09
9020-02-09
9021-12-09
9030-03-09
9040-04-09
9050-05-09
9060-06-09
9070-07-09
9080-08-09
9090-09-09
9101-10-19
9110-01-19
9111-11-19
9120-02-19
9121-12-19
9130-03-19
9140-04-19
9150-05-19
9160-06-19
9170-07-19
9180-08-19
9190-09-19
9201-10-29
9210-01-29
9211-11-29
9220-02-29
9221-12-29
9230-03-29
9240-04-29
9250-05-29
9260-06-29
9270-07-29
9280-08-29
9290-09-29

Java TimeZone and Linux TimeZone Daylight Savings doesnot match

I need to create POSIX format of TimeZone as defined by the following format.
std offset dst [offset],start[/time],end[/time]
For ex for "America/New_York" the POSIX format is
EST+5EDT,M3.2.0/2,M11.1.0/2
Now the value M3.2.0/2 is represented in the form Mm.w.d/t.
This specifies day d of week w of month m. The day d must be between 0 (Sunday) and 6. The week w must be between 1 and 5; week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12. I borrowed the above explanation from the following link
http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
So the above example states, the normal offset from UTC is 5 hours; since this is west of the prime meridian, the sign is positive. Summer time begins on March’s second Sunday at 2:00am and ends on November’s first Sunday at 2:00am.
When I check this in Linux timezone file /usr/share/zoneinfo/America/New_York, it matches the above value
EST5EDT,M3.2.0,M11.1.0
However when I construct this in java for timezone "America/New_York" I get the following string
EST-5EDT+1,M2.1.1/2,M10.1.1/2
I constructed the above string by extracting the information from the output of the following code.
TimeZone timezone = TimeZone.getTimeZone("America/New_York");
System.out.println(timezone.toString());
The output is as below
sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]
Notice the values endMonth=10 which should be 11 as compared to Linux output.
Relying on the output of toString is not advisable, since there are no contractual guarantees about its format in either the TimeZone or SimpleTimeZone classes.
Obviously, your month numbers are off by one; the week of the month isn’t quite as simple, since you need to take into account the first full week of the month.
I would use Java’s documented public methods to get the information:
static String posixSpecFor(TimeZone tz) {
Formatter posixSpec = new Formatter();
float offset = (float) tz.getRawOffset() / (1000 * 60 * 60) * -1;
posixSpec.format("%s%s%s",
tz.getDisplayName(false, TimeZone.SHORT),
offset >= 0 ? "+" : "",
new DecimalFormat("0.##").format(offset));
if (tz.observesDaylightTime()) {
posixSpec.format("%s", tz.getDisplayName(true, TimeZone.SHORT));
}
ZoneId zone = tz.toZoneId();
TemporalField weekOfMonth =
WeekFields.of(DayOfWeek.SUNDAY, 7).weekOfMonth();
int thisYear = Year.now(zone).getValue();
List<ZoneOffsetTransitionRule> rules =
zone.getRules().getTransitionRules();
if (rules.size() > 2) {
rules = rules.subList(0, 2);
}
for (ZoneOffsetTransitionRule rule : rules) {
posixSpec.format(",M%d.%d.%d/%s",
rule.getMonth().getValue(),
rule.createTransition(thisYear).getDateTimeBefore().get(
weekOfMonth),
rule.getDayOfWeek().getValue() % 7,
rule.getLocalTime());
}
return posixSpec.toString();
}
Following is the complete code that I am using to construct Posix timezone string
public class PosixTimeZone {
public String toPosixTZ(String timezoneStr) {
TimeZone timezone = TimeZone.getTimeZone(timezoneStr);
sop("timezoneStr", timezoneStr);
String posixTX = "";
PosixTimeZoneData pTZData = new PosixTimeZoneData(timezone);
if (timezone.useDaylightTime()) {
posixTX = getPosixDSString(pTZData);
} else {
posixTX = getPosixString(pTZData);
}
return posixTX;
}
public static void main(String args[]) {
System.out.println("Posix TimeZone is " + new PosixTimeZone().toPosixTZ(args[0]));
}
private void sop(String varname, String meesage) {
System.out.println("**************: " + varname + " = " + meesage);
}
private String getPosixDSString(PosixTimeZoneData pTZData) {
String posixString = "";
if ((pTZData.std != null && !pTZData.std.isEmpty())
&& (pTZData.stdOffset != null)//&& !pTZData.stdOffset.isEmpty())
&& (pTZData.dst != null && !pTZData.dst.isEmpty())
&& (pTZData.dstOffset != null)// && !pTZData.dstOffset.isEmpty())
&& (pTZData.start != null && !pTZData.start.isEmpty())
&& (pTZData.end != null && !pTZData.end.isEmpty())) {
posixString = String.format("%s%s%s%s,%s,%s", pTZData.std, pTZData.stdOffset, pTZData.dst,
pTZData.dstOffset, pTZData.start, pTZData.end);
} else {
sop("Error", "Invalid Parameters");
}
return posixString;
}
private String getPosixString(PosixTimeZoneData pTZData) {
String posixString = "";
if ((pTZData.std != null && !pTZData.std.isEmpty())
&& (pTZData.stdOffset != null && !pTZData.stdOffset.isEmpty())) {
posixString = String.format("%s%s", pTZData.std, pTZData.stdOffset);
} else {
sop("Error", "Invalid Parameters");
}
return posixString;
}
class PosixTimeZoneData {
String std = "";
String stdOffset = "";
String dst = "";
String dstOffset = "";
String start = "";
String end = "";
private PosixTimeZoneData(TimeZone timeZone) {
std = timeZone.getDisplayName(false, TimeZone.SHORT);
int rawOffset = (timeZone.getRawOffset() / 3600000) * -1;
stdOffset = (rawOffset >= 0)
? ((rawOffset == 0) || (rawOffset == 1) ? "" : "+" + rawOffset)
: "" + rawOffset;
if (timeZone.useDaylightTime()) {
dst = timeZone.getDisplayName(true, TimeZone.SHORT);
int dstRawOffset = timeZone.getDSTSavings() / 3600000;
dstOffset = (dstRawOffset >= 0)
? ((dstRawOffset == 0) || (dstRawOffset == 1) ? "" : "+" + dstRawOffset)
: "" + dstRawOffset;
ZoneId zone = timeZone.toZoneId();
TemporalField weekOfMonth
= WeekFields.of(DayOfWeek.SUNDAY, 7).weekOfMonth();
int thisYear = Year.now(zone).getValue();
List<ZoneOffsetTransitionRule> rules
= zone.getRules().getTransitionRules();
if (rules != null && !rules.isEmpty()) {
if (rules.size() > 2) {
rules = rules.subList(0, 2);
}
start = String.format("M%d.%d.%d/%s",
rules.get(0).getMonth().getValue(),
rules.get(0).createTransition(thisYear).getDateTimeBefore().get(
weekOfMonth),
rules.get(0).getDayOfWeek().getValue() % 7,
rules.get(0).getLocalTime().getHour());
end = String.format("M%d.%d.%d/%s",
rules.get(1).getMonth().getValue(),
rules.get(1).createTransition(thisYear).getDateTimeBefore().get(
weekOfMonth),
rules.get(1).getDayOfWeek().getValue() % 7,
rules.get(1).getLocalTime().getHour());
}
}
}
}
}

How to determine a date in between Friday and Sunday of the week at a particular time

I'm trying to check a current date and time is in between Friday 17:42 and Sunday 17:42 of the week with Java.
At the moment I'm doing this with really really bad code block. It was a hurry solution. Now I'm refactoring but I couldn't find any method in joda or etc.
Any ideas?
Thanks
private final Calendar currentDate = Calendar.getInstance();
private final int day = currentDate.get(Calendar.DAY_OF_WEEK);
private final int hour = currentDate.get(Calendar.HOUR_OF_DAY);
private final int minute = currentDate.get(Calendar.MINUTE);
if (day != 1 && day != 6 && day != 7) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
if (day == 6 && hour > 16) {
if (hour == 17 && minute < 43) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
return badge == 0;
}
} else if (day == 6 && hour < 17) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else if (day == 1 && hour > 16) {
if (hour == 17 && minute < 43) {
return badge == 0;
} else {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
}
} else {
return badge == 0;
}
}
I've used the solution like thiswith the help of #MadProgrammer and #Meno Hochschild
Method:
public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
return ((check.equals(startTime) || check.isAfter(startTime)) && (check.equals(endTime) || check.isBefore(endTime))); }
Usage:
static LocalDateTime now = LocalDateTime.now();
static LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 41);
static LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);
if (!isBetween(now, friday, sunday)) { ... }
Thanks again for your efforts.
Date and Calendar have methods that can perform comparisons on other instances of Date/Calendar, equals, before and after
However, I'd encourage the use of Java 8's new Time API
public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
return ((check.equals(startTime) || check.isAfter(startTime)) &&
(check.equals(endTime) || check.isBefore(endTime)));
}
Which will return true if the supplied LocalDateTime is within the specified range inclusively.
Something like...
LocalDateTime start = LocalDateTime.now();
start = start.withDayOfMonth(26).withHour(17).withMinute(42).withSecond(0).withNano(0);
LocalDateTime end = start.plusDays(2);
LocalDateTime check = LocalDateTime.now();
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = start;
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = end;
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = start.plusDays(1);
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = end.plusMinutes(1);
System.out.println(check + " is within range = " + isBetween(check, start, end));
Which outputs
2015-06-25T18:31:32.969 is within range = false
2015-06-26T17:42 is within range = true
2015-06-28T17:42 is within range = true
2015-06-27T17:42 is within range = true
2015-06-28T17:43 is within range = false
Joda-Time has an Interval class which makes it even eaiser
Interval targetInterval = new Interval(targetStart, targetEnd);
System.out.println("Contains interval = " + interval.contains(targetInterval)
which is demonstrated here
A different approach...
So I was thinking on way home, assuming all you have is the date/time you want to check, how you might determine if the day falls within your range
LocalDateTime now = LocalDateTime.now();
boolean isBetween = false;
switch (now.getDayOfWeek()) {
case FRIDAY:
case SATURDAY:
case SUNDAY:
LocalDateTime lastFriday = getLastFriday(now);
LocalDateTime nextSunday = getNextSunday(now);
isBetween = isBetween(now, lastFriday, nextSunday);
System.out.println(lastFriday + " - " + nextSunday + ": " + end);
break;
}
What this does is checks the dayOfWeek to see if it's within the desired range, if it is, it finds the previous Friday and next Sunday from the specified date and checks to see if it falls between them (see the previous example)
lastFriday and nextSunday simply adds/subtracts a day from the specified date/time until to reaches the desired dayOfWeek, it then seeds the required time constraints
public static LocalDateTime getLastFriday(LocalDateTime anchor) {
LocalDateTime ldt = LocalDateTime.from(anchor);
return ldt.with(DayOfWeek.FRIDAY).withHour(17).withMinute(42).withSecond(0).withNano(0);
}
public static LocalDateTime getNextSunday(LocalDateTime anchor) {
LocalDateTime ldt = LocalDateTime.from(anchor);
return ldt.with(DayOfWeek.SUNDAY).withHour(17).withMinute(42).withSecond(0).withNano(0);
}
With Calendar you can know what DAY_OF_WEEK is the given date, then simply check the hours:
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// in friday the hour must be greater than 17:42
if (dayOfWeek == 5 && ((hour > 17) || (hour == 17 && minute >= 42)) {
// successss!!
}
// days from 1 to 7... saturday(6) all day
if (dayOfWeek == 6) {
// successss!!
}
// sunday hour must be lower than 17:42
if (dayOfWeek == 7 && ((hour < 17) || (hour == 17 && minute <= 42)) {
// successss!!
}
A better solution using old Java would look like this:
// current timestamp
GregorianCalendar gcal = new GregorianCalendar();
// specify ISO-week (you are searching for friday until sunday in this order)
gcal.setMinimalDaysInFirstWeek(4);
gcal.setFirstDayOfWeek(Calendar.MONDAY);
// sunday at 17:43
GregorianCalendar sunday = (GregorianCalendar) gcal.clone();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
sunday.set(Calendar.HOUR_OF_DAY, 17);
sunday.set(Calendar.MINUTE, 43);
sunday.set(Calendar.SECOND, 0);
sunday.set(Calendar.MILLISECOND, 0);
// friday at 17:42
GregorianCalendar friday = (GregorianCalendar) sunday.clone();
friday.add(Calendar.DATE, -2);
friday.add(Calendar.MINUTE, -1);
// logging for test purposes
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(f.format(friday.getTime()));
System.out.println(f.format(gcal.getTime()));
System.out.println(f.format(sunday.getTime()));
// result (assumption: half-open-interval)
boolean withinTimeWindow = !gcal.before(friday) && gcal.before(sunday);
Java-8 offers a shorter approach (assuming ISO-weekmodel):
LocalDateTime now = LocalDateTime.now();
LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 42);
LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);
boolean withinTimeWindow = !now.isBefore(friday) && now.isBefore(sunday);
Finally your equivalent evaluation can look like this:
if (!withinTimeWindow) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
return badge == 0;
}

Need time difference with string like "A Min ago" or "An Hour Ago" [duplicate]

This question already has answers here:
How to calculate "time ago" in Java?
(33 answers)
Closed 8 years ago.
I am new in Android Development.
I need one help to convert my current time with one static time.
Your help be appreciated.
I have one string like this
String created_at = "Wed Mar 03 19:37:35 +0000 2010";
I want to convert it like , which means difference between my current time and created_at string.
23 mins ago // Example
Thanks,
Dharmik
Just use the following utility class I've created and pass the two date objects in its constructor .Subsequently use the getDifferenceString() method to obtain the same.
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Date curdate, Date olddate) {
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? " year" : " years") + " ago");
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? " month" : " months") + " ago");
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? " day" : " days") + " ago");
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? " hour" : " hours") + " ago");
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? " minute" : " minutes") + " ago");
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? " second" : " seconds") + " ago");
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
its is simple do something like this ( Note I don't have java etc installed I have just typed it in Note on my ipad, so I am not sure if it works but it should be something like this) :
String dateString = "Wed Mar 03 19:37:35 2010";
SimpleDateFormat dateFormat = new SimpleDateFormat("E M d hh:mm:ss y");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// convert date to calnedar
Calendar previouseCal = Calendar.getInstance();
previouseCal.setTime(convertedDate );
// then get the current time
Calendar currentCal = Calendar.getInstance();
// then get the diffrence
long difference = currentCal.getTimeInMillis() - previouseCal.getTimeInMillis();
// if you need it in second then
int second = TimeUnit.MILLISECONDS.toSeconds(difference)
I hope that helps :)

Converting date into text format

How do I convert date into its text format..for ex:if updated today..then instead of date it must show "Today",one day after it must show "Yesterday",and then after two days..it must display the date in general form(//_) on which it was updated..i tried using SimpleDateFormat..but not working..
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d= new Date();
//Convert Date object to string
String strDate = sdf.format(d);
System.out.println("Formated String is " + strDate);
d = sdf.parse("31-12-2009");
Plz help..
Thanks in advance..
Try this:
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}
Take a look at the PrettyTime library.
You can check this Comparision of dates
import java.text.SimpleDateFormat;
import java.util.Date;
public class App {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public static long ms, s, m, h, d, w;
static {
ms = 1;
s = ms * 1000;
m = s * 60;
h = m * 60;
d = h * 24;
w = d * 7;
}
public App() {
Date now = new Date();
Date old = new Date();
try {
old = sdf.parse("12-11-2013");
} catch (Exception e) {
e.printStackTrace();
}
long diff = now.getTime() - old.getTime();
if (diff < this.d) {
System.out.println("Today");
}
else if (diff > this.d && diff < this.d*2) {
System.out.println("Yesterday");
}
System.out.println("Difference: " + msToHms(diff));
}
public String msToHms(long ms) {
int seconds = (int) (ms / this.s) % 60 ;
int minutes = (int) ((ms / this.m) % 60);
int hours = (int) ((ms / this.h) % 24);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
new App();
}
}
Output
Yesterday
Difference: 07:11:22
You have to implement your own logic based on the time difference and use the corresponding date format.
Lets assume you are getting a date from a server.
Get the device's time and compare to your date.
For your requirements there will be two cases.
The difference between the two date is less then a day, then return "Today" string.
The difference between the two date is grater then a day then use the Simple Date format to format your date as you want.
For comparing dates please see this entry: datecompare

Categories