How to calculate date in kotlin with the given format? - kotlin

How to see if a user can be unbanned or not between 2 dates?
Hi, I have a given variable which is the date the user was unbanned as end_banned in the format HH:mm:ss dd/MM/YYYY.
val end_banned: String= "15:05:00 12/01/2022"
I want to calculate if at the current time they can be unbanned or not. I have tried with SimpleDateFormat, Calendar, Date... but still haven't found a solution.
I've tried separating each element of seconds, minutes, days... and comparing them with if...else like this:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var _hours = cal.get(Calendar.HOUR)
var _minutes = cal.get(Calendar.MINUTE)
var _seconds = cal.get(Calendar.SECOND)
var _day = cal.get(Calendar.DAY_OF_MONTH)
var _month = cal.get(Calendar.MONTH) + 1
var _year = cal.get(Calendar.YEAR)
var hours = end_banned.toString().substring(0, 2).toInt()
var minutes = end_banned.toString().substring(3, 5).toInt()
var seconds = end_banned.toString().substring(6, 8).toInt()
var day = end_banned.toString().substring(9, 11).toInt()
var month = end_banned.toString().substring(12, 14).toInt()
var year = end_banned.toString().substring(15).toInt()
if (_year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes && _seconds >= seconds
|| _year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes
|| _year >= year && _month >= month && _day >= day && _hours >= hours
|| _year >= year && _month >= month && _day >= day
|| _year >= year && _month >= month
|| _year >= year) {
println("True")
} else {
println("False")
}
But it is only true for the first 3 conditions when there are hours, minutes and seconds.
I tried with SimpleDateFormat and Date like this:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var hours = cal.get(Calendar.HOUR)
var minutes = cal.get(Calendar.MINUTE)
var seconds = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var sdf_unbanned = sdf.parse(end_banned)
var sdf_now = sdf.parse("${hours}:${minutes}:${seconds} ${day}/${month}/${year}")
if (sdf_now.time - sdf_unbanned.time <= 0) {
println(true)
} else {
println(false)
}
But this condition always gives an incorrect number if I adjust the now and unbanned variables a few minutes apart (This makes it easier to spot)

I did not fully understand your question Sir, But I assume you want to compare unbanned_date to the current date (now time) if they are the same(we reached the unban date) then it should unban whatever you are unbanning, If so the implementation requires less code to achieve that ,Like this :
val sdf = SimpleDateFormat("dd/MM/yyyy")
val strDate: Date = sdf.parse(end_banned)
if (System.currentTimeMillis() > strDate.getTime()) {
urbanUser = true // or what ever your logic is
}

Shame, I got confused between cal.get(Calendar.HOUR) and cal.get(Calendar.HOUR_OF_DAY)
Because cal.get(Calendar.HOUR) returns only 12h format
And cal.get(Calendar.HOUR_OF_DAY) will return 24h format
I found a workaround and here is the code that I fixed and tested:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var hour = cal.get(Calendar.HOUR_OF_DAY)
var minute = cal.get(Calendar.MINUTE)
var second = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var now: Date? = sdf.parse("${hour}:${minute}:${second} ${day}/${month}/${year}")
var end: Date? = sdf.parse(end_banned)
return now?.time!! > end?.time!!
Thanks for the help.

Related

why no result when change month in sqflite and flutter?

when i run this code in same month it work correctly but when the dates not a same month i don't have result []
for example
start date: 2023-01-28T00:00:00.000
end date: 2023-01-30T00:00:00.000
work correctly and
start date: 2023-01-28T00:00:00.000
end date: 2023-02-02T00:00:00.000
not working
Future<List> tPeriod(String startDate, String endDate) async{
var start = DateFormat('yMMMd HH:mm').parse(startDate);
print('start date: $start');
var end = DateFormat('yMMMd HH:mm').parse(endDate);
print('end date: $end');
int comparison = start.compareTo(end);
print('Comparison result: $comparison');
if (comparison > 0 ) {
print('Error: Start date is after end date');
return [];
}
var db = await database;
var result = await db.rawQuery("SELECT $colName FROM $Table WHERE $colDate BETWEEN '$startDate' AND '$endDate' ORDER BY RANDOM() LIMIT 1");
print('$result');
return result.toList();
}

How do I extract current date, month and year in the format yyyy-mm-dd in karate dsl?

* def date =
"""
function(s) {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return sdf.parse(s).time;
}
"""
Currently, I'm using this. Any help is much appreciated.
You can also archive the following by using javascript as follows:
* def todaysDate =
"""
function()
{
var d=new Date();
var month = String(d.getMonth() + 1);
var day = String(d.getDate());
var year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return year+'/'+month+'/'+day
}
"""
* print todaysDate()
Here you go:
* def today =
"""
function() {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat('yyyy-MM-dd');
return sdf.format(new java.util.Date());
}
"""
* print today()

How to update date month and year in datepicker andriod studio kotlin

Day,year and month using these given values after being updated.
I want them to use updated values please help.
var day = 1
var month = 1
var year = 1999
val dpd = DatePickerDialog(this,android.R.style.Theme_Holo_Dialog,
DatePickerDialog.OnDateSetListener { datePicker, selyear,
monthOfYear, dayOfMonth ->
day = dayOfMonth
month = monthOfYear
year = selyear
tv.text = "$day - $month - $year" /*printing day month year*/
}, year, month, day
)
dpd.show()
val pday = 30 - day /* day = 1(Not the chosen value)*/
val pmonth = 12 - month
val pyear = 2019 - year
Change the variable declarations from val to var and update them inside the listener:
val c = Calendar.getInstance()
var day = c.get(Calendar.DAY_OF_MONTH)
var month = c.get(Calendar.MONTH)
var year = c.get(Calendar.YEAR)
val dpd = DatePickerDialog(
this,
android.R.style.Theme_Holo_Dialog,
DatePickerDialog.OnDateSetListener { datePicker, selyear, monthOfYear, dayOfMonth ->
day = dayOfMonth
month = monthOfYear + 1
year = selyear
tv.text = "$day - $month - $year"
}, year, month, day
)
dpd.show()

How to select all the days of the week from a given day?

Given a date I want to get all the other days of that same week, where in the week starts and ends on Saturday and Friday.
Model
public TimeModel
{
public int ID
public DateTime Day
}
What I'm currently doing
public Contrller{
private db = new ModelContext();
public AddDates(DateTime Date)
{
List<Model> list = new List<Model>();
int n = 0;
while(Date.DayofWeek != DayofWeek.Sauturday)
Date = Date.AddDats(-1) // keep subracting the date until I reach Saturday
while(Date.DayofWeek != DayofWeek.Friday
{
list.Add(Find(Date));
//Simply put for each date not Friday
// I find the corresponding model (the one with the same date)
//and add it to the list
Date = Date.AddDays(1)
}
list.Add(Find(Date)); // To add the Friday date to list
}
Note: Not exactly my code, just a simplification of my problem.
To summarize my solution:
a) Subtract given date until Saturday
b) Find model which corresponds to Date
c) Repeat until I reach Friday
d) Add to list once more to include Friday
Is it possible to create a linq/sql statement to simpyly select the needed models (with regards to Date)?
You can find a sample implementation that gets the current week.
List<TimeModel> list = new List<TimeModel>();
int n = 0;
for (int i = 0; i < 200; i++)
list.Add(new TimeModel{ID = i, Day = DateTime.Now.AddDays(-i)});
var currentDay = new TimeModel() {ID = 0, Day = DateTime.Now};
var previousSaturday = currentDay.Day.AddDays(-(int)currentDay.Day.DayOfWeek - 1);
var nextFriday = previousSaturday.AddDays(6);
var currentWeek = list.Where(p => p.Day.DayOfYear >= previousSaturday.DayOfYear && p.Day.DayOfYear <= nextFriday.DayOfYear).OrderBy(p => p.Day.DayOfYear).ToList();

Refreshing view panel from dojo widget

Got this code from #MichaelSaiz and altered it slightly, and the calendar widget looks/works great with the Calendar.css that comes with dojo 1.5.x on the Domino server.
However, I need to refresh a Calendar view when the user clicks on a date, and although fields are being refreshed OK, the view is behaving strangely, and I can't see why?
XSP.addOnLoad(function(){
dojo.require("dojox.widget.Calendar");
dojo.require("dojo.date","dijit.registry");
dojo.require("dojo.date.locale");
dojo.require("dijit.Calendar");
dojo.ready(function(){
// create the Calendar:
var selectedDate = null;
var calendar_body = new dojox.widget.Calendar({
value: new Date(),
onValueSelected: function(date){calendarDateClicked(date);
}
}, "calendar_body");
//create Click action
function calendarDateClicked(date){
var d = new Date(date);
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var dateString = [day,month,year].join("/");
var y = dojo.date.locale.format(d, {datePattern:"dd/MM/yyyy", selector: 'date'});
//dojo.byId('#{id:hiddenCalWidgetSelectedDate}').value = dateString
dojo.byId('#{id:hiddenCalWidgetSelectedDate}').value = y;
dojo.byId('#{id:calDate}').value = y;
//dojo.byId('#{id:calDate}').value = dateString;
XSP.partialRefreshGet("#{id:dayPanel1}",{});//Post Value to server
}
});
});
This fires when the user clicks the calendar and it updates a field (calDate) and then updates the viewPanel (dayPanel1).
The view is filtered based on a calDate field which clicking on the calendar sets.
Any ideas how I can get the view refreshed when the user clicks on the calendar? Seems basic but it's driving me nuts!!
Graeme
The date format was incorrect (as #MichaelSaiz surmised). Got it sorted now.
XSP.addOnLoad(function(){
dojo.require("dojox.widget.Calendar");
dojo.require("dojo.date","dijit.registry");
dojo.require("dojo.date.locale");
dojo.require("dijit.Calendar");
dojo.ready(function(){
// create the Calendar:
var selectedDate = null;
var calendar_body = new dojox.widget.Calendar({
value: new Date(),
onValueSelected: function(date){calendarDateClicked(date);
}
}, "calendar_body");
//Set month in correct format
function setMonth(month){
switch(month)
{
case 1:
month = "Jan";
break;
case 2:
month = "Feb";
break;
}
return month;
}
//create Click action
function calendarDateClicked(date){
var d = new Date(date);
var month = (d.getMonth() + 1);
month = setMonth(month);
var day = '' + d.getDate() + ",";
var year = d.getFullYear();
//if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var dateString = [month,day,year].join(" ");
//var y = dojo.date.locale.format(d, {datePattern:"dd/MM/yyyy", selector: 'date'});
dojo.byId('#{id:hiddenCalWidgetSelectedDate}').value = dateString
//dojo.byId('#{id:hiddenCalWidgetSelectedDate}').value = y;
//dojo.byId('#{id:calDate}').value = y;
dojo.byId('#{id:calDate}').value = dateString;
XSP.partialRefreshPost("#{id:mainPanel}",{});//Post Value to server
}
});
});