I have a code that supports only API Level >= 26 in android:
public static String in = "7:00:00";
public static String in_until = "11:50:00";
public static String breakout_out = "11:51:00";
public static String breakout_out_until = "12:50:00";
public static String breakout_in = "12:51:00";
public static String breakout_in_until = "13:10:00";
public static String out = "16:50";
public static String getCurrentTimeLogType() {
// LocalTime target = LocalTime.parse( DataHandler.timestamp().split(" ")[1] ) ;
LocalTime target = LocalTime.parse("7:30:00") ;
if (target.isBefore(in) || (target.isAfter(in) && target.isBefore(in_until)))
return "TIME-IN";
else if (target.isAfter(breakout_out) && target.isBefore(breakout_out_until))
return "BREAK-OUT";
else if (target.isAfter(breakout_in) && target.isBefore(breakout_in_until))
return "BREAK IN";
else if (target.isAfter(out))
return "TIME-OUT";
return "UNKNOWN!";
}
I want to return if the specified time in the variables is within the current time to return what type of timestamp to add to database.
For example if today is 12:05 PM:
if (12:05 >= breakout_out && 12:05 <= breakout_out_until)
return "BREAK-OUT"
I want to achieve something like this. How can I achieve a code like this without using the unsupported LocalTime module?
What about something like below. Not tested though.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date breakout_out = sdf.parse("11:51:00");
Date breakout_out_until = sdf.parse("13:10:00");
Date current_time = sdf.parse("12.05.00");
if(current_time.before(breakout_out_until) && current_time.after(breakout_out)) {
return "BREAK-OUT"
}
Related
I wanted to do a date range search in java suppose I wanted to search from 10-22-2019 to the present date.
But the question is to do the date range search in the chunk size of two weeks(consider this can vary but in form weeks) for eg here start date will 10-22-2019 but the end date will start date + 2 weeks added to it after the date range search is done for this and taking the result. Now the new start date should be were the previous date range search ended. and the end date should be now 2 weeks from the new start date again the search and this keeps on until I get till the present date.
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}
Got this from one of the answers but have trouble in implementing in my situtation.
Simple iterative solution :
LocalDate start = LocalDate.parse("2019-10-22");
LocalDate end = LocalDate.now();
LocalDate chunckStart = start;
while (chunckStart.plusDays(15).isBefore(end)) {
doTheThing(chunckStart, chunckStart.plusDays(15));
chunckStart = chunckStart.plusDays(16);
}
doTheThing(chunckStart, end);
You can try it here.
try:
public static Iterator<Pair<LocalDate, LocalDate>> splitDataRange(LocalDate start, LocalDate end, int dayChunkSize) {
return new Iterator<Pair<LocalDate, LocalDate>>() {
private LocalDate chunkStart = start;
private LocalDate chunkEnd = start.plusDays(dayChunkSize);
#Override
public boolean hasNext() {
return end.compareTo(chunkEnd) > 0;
}
#Override
public Pair<LocalDate, LocalDate> next() {
Pair<LocalDate, LocalDate> chunk = new Pair<>(chunkStart, chunkEnd);
chunkStart = chunkEnd;
chunkEnd = chunkEnd.plusDays(dayChunkSize);
return chunk;
}
};
}
public static void main(String[] args) {
Iterator<Pair<LocalDate, LocalDate>> periodIterator = splitDataRange(LocalDate.of(2019, 3, 1),
LocalDate.of(2019, 5, 1), 20);
while (periodIterator.hasNext()) {
Pair<LocalDate, LocalDate> startEnd = periodIterator.next();
System.out.println(String.format("from %s to %s"
, startEnd.getValue0(), startEnd.getValue1()));
}
}
The Pair api is from:
<dependency>
<groupId>org.javatuples</groupId>
<artifactId>javatuples</artifactId>
<version>1.2</version>
</dependency>
Here's a solution using Streams and LocalDate:
LocalDate start = LocalDate.of(2020, 2, 28);
LocalDate end = LocalDate.now();
int step = 7;
start
.datesUntil(end, Period.ofDays(step))
.map(date -> {
LocalDate proposedEnd = date.plusDays(step);
LocalDate chunkEnd = proposedEnd.compareTo(end) > 0 ? end : proposedEnd;
return new SimpleEntry<>(date, chunkEnd);
})
.forEach(chunk -> System.out.println(chunk.getKey() + " until " + chunk.getValue()));
It generates the same output as the corresponding C# program.
The datesUntil method requires Java 9. Otherwise, if you're using Java 8, then you could use a helper method instead:
public static Stream<LocalDate> datesUntil(LocalDate from, LocalDate toExclusive) {
long daysBetween = ChronoUnit.DAYS.between(from, toExclusive);
return Stream.iterate(from, t -> t.plusDays(1))
.limit(daysBetween);
}
Assume that I have a data input like this:
018492114,51863406,X0,1,20160218
018529816,51864472,X0,1,20150603
018543434,51864629,X0,1,20150702
018543464,51864990,N5+,1,2015063
018530309,51865142,X0,1,20150603
I want only to convert the 5 column's element to Date format because it was imported as a string. And I want to do a sorting operation by DA_PRM_CTR_ORDER variable (the end column).
Note that I am using arraylist object defined as Personne and I am using Comparable interface to use Comparable method for sorting:
this is my class personne which includes the needed object:
public class Personne implements Comparable {
private String IDC_PSE_PCL;
private String IDC_CD_NOT;
private String CD_NOTE;
private String IDT_ETT_PSE;
private String DA_PRM_CTR_ORDER;
public Personne(String IDC_PSE_PCL, String IDC_CD_NOT,
String DA_PRM_CTR_ORDER, String IDT_ETT_PSE, String CD_NOTE) {
this.IDC_PSE_PCL = IDC_PSE_PCL;
this.IDC_CD_NOT = IDC_CD_NOT;
this.IDT_ETT_PSE = IDT_ETT_PSE;
this.CD_NOTE = CD_NOTE;
this.DA_PRM_CTR_ORDER = DA_PRM_CTR_ORDER;
}
public String getIDC_CD_NOT() {
return this.IDC_CD_NOT;
}
public String getIDC_PSE_PCL() {
return this.IDC_PSE_PCL;
}
public String getDA_PRM_CTR_ORDER() {
return this.DA_PRM_CTR_ORDER;
}
public String getIDT_ETT_PSE() {
return this.IDT_ETT_PSE;
}
public String getCD_NOTE() {
return this.CD_NOTE;
}
#Override
public int compareTo(Object o) {
Personne other = (Personne) o;
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date converted = (Date) df.parse(other.getDA_PRM_CTR_ORDER());
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
// Si Egalite des dates
if (res == 0) {
res = IDT_ETT_PSE.compareTo(other.getIDT_ETT_PSE());
}
return res;
}
My problem is in the line:
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
when I want to sort by DA_PRM_CTR_ORDER values but it show me this problem:
The method compareTo(String) in the type String is not applicable for
the arguments (Date)
How can I resolve this issue please?
A quick fix could be to parse this.DA_PRM_CTR_ORDER to Date too. So the line you highlighted would look like:
int res = df.parse(this.DA_PRM_CTR_ORDER).compareTo(converted);
you should use Date.compareTo(Date) instead of String.compareTo(Date).
suggestion:
Long currentDate = Long.parseLong(this.DA_PRM_CTR_ORDER);
return currentDate.compareTo(Long.parseLong(other.getDA_PRM_CTR_ORDER()));
It would be better if you compare the timestamp of two dates to compare.
Date self = (Date) df.parse(this.getDA_PRM_CTR_ORDER());
String ConvertedTs = String.valueOf(converted.getTime());
String selfTs = String.valueOf(self.getTime());
int res = selfTs.compareTo(ConvertedTs);
I have below method in which different date patterns have been handled
below is the method in which different date formats have been handled now
now for the particulat format YYYY-MM-dd i don't want it to go for the check where we are prefixing 20 before in code please advise how can i skip that part lets say if the date pattern is YYYY-MM-dd then avoid the logic of prefixing 20 in front of year
below is my code
public java.util.Date extractDate(String dateStr, String dateType) {
String[] datePatternsOfUk = { "d-M-yy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-MM-dd","dd-MM-yy", "dd-MMM-yy","dd-MMM-yyyy","dd-MM-yyyy",
"dd/MM/yy","dd/MMM/yy","dd/MMM/yyyy"};
String[] datePatternsOfUs = { "M-d-yy","MM-dd-yy","M/d/yy","MM/dd/yy", "MM/dd/yy", "MMM-dd-yy",
"MMM/dd/yy", "MMM-dd-yyyy", "MM-dd-yyyy", "MMM/dd/yyyy",
"MM/dd/yyyy" };
java.util.Date date = null;
String[] datePatterns = datePatternsOfUk;
if (dateType.equals("US")) {
datePatterns = datePatternsOfUs;
} else if (dateType.equals("UK")) {
datePatterns = datePatternsOfUk;
}
///******code should not go in this check where date pattern is YYYY-MM-dd
int p = dateStr.lastIndexOf("/");
if (p == -1) {
p = dateStr.lastIndexOf("-");
}
String firstSubstring = dateStr.substring(0, p + 1);
String secondSubstring = dateStr.substring(p + 1);
if (p != -1 && secondSubstring.length() <= 2) {
secondSubstring = Integer.toString(2000 + Integer.parseInt(secondSubstring));
dateStr = firstSubstring + secondSubstring;
}
///****************************************//
try {
date = DateUtils.parseDate(dateStr, datePatterns);
} catch (ParseException ex) {
logger.error("##$$$$$### Error in invoice inside extractDate method : ##$$$$$$#### "
+ ErrorUtility.getStackTraceForException(ex));
}
return date;
}
You could avoid trying any inappropriate pattern by checking if the string "looks like" the pattern before parsing with the pattern.
The general way to do this is:
String datePattern = "yyyy-MM-dd"; // for example
String input;
if (input.matches(datePattern.replaceAll("\\w", "\\d"))) {
// the input looks like the pattern
// in this example "dddd-dd-dd" where "d" is any digit
// so go ahead and try the parse
}
You can enhance this logic to add:
if (input.matches("\\d\\d\\D.*")) {
// then it only has a two digit year, so add "20" to the front
}
if (!dateStr.equals("YYYY-MM-dd")) {
// code
}
I need a timezone display values as follows :
(UTC + 05:30) Chennai, Kolkata, Mumbai, New Delhi
But by using following method I am getting bit different output. How should I get the timezone display name as above ? (if required, I can use JODA).
public class TimeZoneUtil {
private static final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private static List<TimeZone> timeZones;
public static List<TimeZone> getTimeZones() {
if (timeZones == null) {
timeZones = new ArrayList<TimeZone>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES)) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
Collections.sort(timeZones, new Comparator<TimeZone>() {
public int compare(final TimeZone t1, final TimeZone t2) {
return t1.getID().compareTo(t2.getID());
}
});
}
return timeZones;
}
public static String getName(TimeZone timeZone) {
return timeZone.getID().replaceAll("_", " ") + " - " + timeZone.getDisplayName();
}
public static void main(String[] args) {
timeZones = getTimeZones();
for (TimeZone timeZone : timeZones) {
System.out.println(getName(timeZone));
}
}
}
This code may do the trick for you:
public static void main(String[] args) {
for (String timeZoneId: TimeZone.getAvailableIDs()) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
// Filter out timezone IDs such as "GMT+3"; more thorough filtering is required though
if (!timeZoneId.matches(".*/.*")) {
continue;
}
String region = timeZoneId.replaceAll(".*/", "").replaceAll("_", " ");
int hours = Math.abs(timeZone.getRawOffset()) / 3600000;
int minutes = Math.abs(timeZone.getRawOffset() / 60000) % 60;
String sign = timeZone.getRawOffset() >= 0 ? "+" : "-";
String timeZonePretty = String.format("(UTC %s %02d:%02d) %s", sign, hours, minutes, region);
System.out.println(timeZonePretty);
}
}
The output looks like this:
(UTC + 09:00) Tokyo
There are, however, a few caveats:
I only filter out timezones whose ID matches the format "continent/region" (e.g. "America/New_York"). You would have to do a more thorough filtering process to get rid of outputs such as (UTC - 08:00) GMT+8 though.
You should read the documentation for TimeZone.getRawOffSet() and understand what it's doing. For example, it doesn't DST effects into consideration.
On the whole, you should know that this is a messy approach, primarily because the timezone ID can be of so many different formats. Maybe you could restrict yourself down to the timezones that matter for your application, and just have a key value mapping of timezone IDs to display names?
I am writing a credit card program. I want the program to use the current date every time the method is used to make a purchase and put the date into the array
private GregorianCalendar transDate;
public CreditCard(double amount,String storeName, GregorianCalendar transDate) {
this.amount=amount;
this.storeName=storeName;
transDate=new GregorianCalendar();
}
public void purchase(double amount, String storeName, GregorianCalendar date)throws Exception
{
if (numPurchases<purchases.length)
if (amount >0 )
if(amount+balance<=creditLimit)
if( GregorianCalendar.getInstance().getTimeInMillis()<=expDate.getTimeInMillis())
{
balance+=amount;
transDate=getTransDate();
purchases[numPurchases] = new CreditCard(amount, storeName,transDate);
numPurchases++;
}
else
{
throw new Exception("card expired");
}
else{
throw new Exception("insufficient credit");
}
else{
throw new Exception("invalid amount");
}
else{
throw new Exception("exceeded number of allowed purchases");
}
}
I would like to display the information in String info
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=transDate.get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n" ;
}
how do I need to set up the code to use the current date and add it to the array and display it in the string
Why don't you use a List implementation instead of an array? You can override the toString method to print it the way you want.
final SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy");
List<Calendar> dates = new ArrayList<Calendar>() {
private static final long serialVersionUID = -5079502477457556887L;
#Override
public String toString() {
Iterator<Calendar> i = iterator();
if (!i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Calendar c = i.next();
sb.append(formatter.format(c.getTime()));
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
};
dates.add(Calendar.getInstance());
dates.add(Calendar.getInstance());
System.out.println(dates);
What does your getTransDate() function do? Ideally it should return the transDate variable of CreditCard object. To calculate transDate for a purchase, you are better off renaming the method to calculateTransDate() or something like that.
Once you have getTransDate() method returning the transDate, your info string can be :
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=purchases[index].getTransDate().get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n"
}