Struggle with parse function - android

So started learning Kotlin and Android studio coding.
I was following Youtube video
https://www.youtube.com/watch?v=z3_QgdmXGK4&t=994s&ab_channel=Dr.ParagShukla
I am making simple age calculator, however, cant make string to become date, so i could subtract input date with current date. Code looks exactly same as in the video.
Code compiles well and gets installed in android device, however, whenever press Calculate Age button, app stops responding because of var dob = sdf.parse(dob) function. I assume it cant convert the date from string to date format for further calculations. Thanks.
Code below:
fun openDatePicker(view: View) {
var c = Calendar.getInstance()
DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { datePicker, yy, mm, dd -> // listens what date picker has to say
var mm = mm + 1
var date = "$dd/ $mm /$yy "
TimePickerDialog(
this,
TimePickerDialog.OnTimeSetListener { timePicker, hh, mi ->
date += " $hh:$mi"
editTextTextPersonName.setText(date) // shows date in the line
},
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
).show()
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)
).show()
}
fun Calculateage(view: View) {
var today = Date() // todays date
var dobs = editTextTextPersonName.text.toString() // takes value from input
var sdf = SimpleDateFormat("mm/MM/yy HH:mm")
var dob = sdf.parse(dobs) // converts the date to simple date, no can find difference
var days = (today.time - dob.time) / 86400000 // converts into mil secs, need to divide by milsecs in a day
var hours = (today.time - dob.time) % 86400000 / 3600000
var minutes = (today.time - dob.time) % 86400000 % 3600000 / 60000
var sec = (today.time - dob.time) % 86400000 % 3600000 % 60000/1000
textView.visibility = View.VISIBLE
textView.setText("Days = $days\nHours= $hours\nMinutes=$minutes\nSeconds = $sec")
}

Your SimpleDateFormat doesn't match your string value.
Your var date looks like var date = "$dd/ $mm /$yy $hh:$mi"
Your SimpleDateFormat has "mm/MM/yy HH:mm"
You should change your formatter to something like this:
"dd/ MM /yy HH:mm"

Related

Android kotlin check is user older than 18

In my app I have 3 edittexts where user enters day (f.e. 23), month (f.e. 09) and year (f.e. 2008).
I would like to know how to determine is user younger or older than 18 years.
How to do this?
PS. Please write your solution in Kotlin
Try this code. I have not tested it but It will give you the desired output. Let me know If not
private int getYears() {
int year = 2008; // get from the year edittext
int month = 9; // get from the month edittext
int day = 23; // get from the date edittext
Calendar c1 = Calendar.getInstance();
c1.set(year, month - 1, day, 0, 0); // as MONTH in calender is 0 based.
Calendar c2 = Calendar.getInstance();
int diff = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) > c2.get(Calendar.MONTH) ||
(c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DATE) > c2.get(Calendar.DATE))) {
diff--;
}
return diff;
}
And here is an equivalent Kotlin funtion
private fun getYears(): Int {
val year = 2008 // get from the year edittext
val month = 9 // get from the month edittext
val day = 23 // get from the date edittext
val c1 = Calendar.getInstance()
c1[year, month - 1, day, 0] = 0 // as MONTH in calender is 0 based.
val c2 = Calendar.getInstance()
var diff = c2[Calendar.YEAR] - c1[Calendar.YEAR]
if (c1[Calendar.MONTH] > c2[Calendar.MONTH] ||
c1[Calendar.MONTH] == c2[Calendar.MONTH] && c1[Calendar.DATE] > c2[Calendar.DATE]
) {
diff--
}
return diff
}
This is the correct solutions to your problem, I hope this will help you
and please import these lines also
import java.time.LocalDate
import java.time.Period
import java.util.Locale
fun isUser18Older(): Boolean {
val todaysDate = LocalDate.now()
val userDob = LocalDate.of(2004, 2, 3) //3-Feb-2004
val yearDiff = Period.between(userDob,todaysDate ).years
return yearDiff >= 18
}
In age control, leap years can confuse our calculations. For this reason, I prepared an algorithm in the simplest way. You can use this extension method without any problems with year, month, day comparisons.
fun Date.isUser18Older(): Boolean {
val toDate = Calendar.getInstance()
val birthDate = Calendar.getInstance()
birthDate.time = this
if (toDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR) > 18) {
return true
}
if (toDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR) == 18) {
if (toDate.get(Calendar.MONTH) > birthDate.get(Calendar.MONTH)) {
return true
}
if (toDate.get(Calendar.MONTH) == birthDate.get(Calendar.MONTH) && birthDate.get(Calendar.DAY_OF_MONTH) <= toDate.get(
Calendar.DAY_OF_MONTH
)
) {
return true
}
}
return false
}
Ref: 1.https://stackoverflow.com/questions/25460965/how-can-i-create-a-date-object-with-a-specific-format
2.https://stackoverflow.com/questions/10690370/how-do-i-get-difference-between-two-dates-in-android-tried-every-thing-and-pos/63207518
I would suggest doing this in a step-by-step approach.
Convert the data to a string in dd/mm/yyyy format
Now create a date object with that in this fashion
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date d= new Date(); //Get system date
//Convert Date object to a string
String strDate = sdf.format(d);
//Convert a String to Date
d = sdf.parse("02/04/2014");
Find the difference between the dates using the following format
long diffInMillisec = date1.getTime() - date2.getTime();
long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);
long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
Convert to years and then check
numyears = Math.floor(diffInSec/ 31536000)
if(numyears>18){
//your code here
}
This is the kotlin implementation of the answerr given by #Bhargav
private fun getUserYears() : Int {
var year = 2003; // get from the year edittext
var month = 4; // get from the month edittext
var day = 30; // get from the date edittext
var c1 = Calendar.getInstance ();
c1.set(year, month - 1, day, 0, 0); // as MONTH in calender is 0 based.
var c2 = Calendar.getInstance();
var diff = c2.get (Calendar.YEAR) - c1.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) > c2.get(Calendar.MONTH) ||
(c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DATE) > c2.get(
Calendar.DATE
))
) {
diff--;
}
return diff;
}

How to get date given only the day of year number in flutter

I am fairly new to flutter. In android, I could easily use the Calendar class set using cal.set(Calendar.DAY_OF_YEAR, number) and it will return the date for that particular day_of_year number. How can I do the same in Flutter.
In Android, this is what I would have done
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_YEAR,1); //set date using day of year
return cal.getTime(); //2020-01-01
How do I implement this in Flutter.
I gave this a go for fun, I don't normally do Dart, so apologies if its wrong!
var dayOfYear = 1;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000
var millisDayOfYear = dayOfYear * millisInADay;
var millisecondsSinceEpoch = DateTime(DateTime.now().year).millisecondsSinceEpoch;
var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch + millisDayOfYear);
For the day of year == 1.
When there are 86400000 milliseconds in a day.
Then there are 86400000 millis in that year (1 x 86400000).
Create a new date for the first day of the year.
Add the number of millis in the year, to the number of millis to the start of the year since epoch. Create a new date using this milliseconds since epoch.
Reference:
https://api.dart.dev/stable/2.7.1/dart-core/DateTime-class.html

Localized time with leading zero

Under my locale DateFormat.getTimeInstance(DateFormat.SHORT).format(...) gives me 8:28 AM. Is there any way to get localized time but with leading zero (that is, 08:28 AM in my case) - I mean without hardcoding pattern etc?
If you want to have 24H format time you can do something like this using kotlin extensions:
fun Long.formatTime(): String? {
val calendar = Calendar.getInstance()
calendar.time = Date(this)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
return String.format("%02d:%02d", hour, minute)
}
EDITED
If you still did't find the solution
val dateFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())
print(dateFormat.format(Date()))
This prints
08:24 AM

How to Get Date only or Time only output in react-native

I am developing an app in react-native.
I am using an npm package called react-native-modal-datetime-picker for collecting date. But the output i am getting is mixture of date and time
'Fri Feb 17 2017 16:06:00 GMT+0530 (IST)'
How cant collect only date in the format format="DD-MM-YY" from this.
I have faced same issues javascript should rename it to DateTime instead of just Date.
I would recommend you to use moment.js it will help you in timezones.
moment(new Date()).format("DD-MM-YYYY");
read more
If you have it as an Javascript Date object you could do this:
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
After that you can format it how you like. Just remember that getMonth() is from (0-11), so you can add one to the result to get it like a "normal" calendar.
var string = day + '-' + month + '-' + year;
onChange = (event, selectedDate) => {
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const currentDate = selectedDate || this.state.date;
this.setState({show: Platform.OS === 'ios'});
this.setState((this.state.date = currentDate));
// console.log('Month', currentDate.getMonth());
console.log('Date', currentDate.getDate());
var monthName = months[currentDate.getMonth()];
console.log(monthName);
// const Date = currentDate.toLocaleString('default', {month: 'long'});
// console.log('Date:', Date);
//Set Date
this.setState({currDate: currentDate.getDate()});
this.setState({currMonth: monthName});
};
For get a date few days forward from today {React TypeScript}: (It's also quite similar for previous date from today)
//This function is for calculating estimated Delivery Date
let date = new Date();
const estimatedDeliveryDate = (date: Date, day: number) => {
date.setDate(date.getDate() + day);
};
estimatedDeliveryDate(date, 3);
var estimatedDate =
date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear();
console.log("Delivery Date: ", estimatedDate);

Dart - How to set the hour and minute of DateTime object

How do I set/change the hour and/or minute of a DateTime object. Similar to Date.setHours(..) in JavaScript.
e.g If i did
var time = DateTime.parse("2018-08-16T11:00:00.000Z");
how do I set the hour and minute of time
var newHour = 5;
time = time.toLocal();
time = new DateTime(time.year, time.month, time.day, newHour, time.minute, time.second, time.millisecond, time.microsecond);
There were discussions to add an update() method that allows to modify specific parts only, but it doesn't look like this has landed.
now with extension u could do something like this
extension MyDateUtils on DateTime {
DateTime copyWith({
int? year,
int? month,
int? day,
int? hour,
int? minute,
int? second,
int? millisecond,
int? microsecond,
}) {
return DateTime(
year ?? this.year,
month ?? this.month,
day ?? this.day,
hour ?? this.hour,
minute ?? this.minute,
second ?? this.second,
millisecond ?? this.millisecond,
microsecond ?? this.microsecond,
);
}
}
I got a simpler solution:
DateTime newDate = DateTime.now();
DateTime formatedDate = newDate.subtract(Duration(hours: newDate.hour, minutes: newDate.minute, seconds: newDate.second, milliseconds: newDate.millisecond, microseconds: newDate.microsecond));
Then the XX:XX from 'formatedDate' should be 00:00
Explanation:
formatedDate is a new DateTime variable with the content of newDate minus hours, minutes... from it
I believe this is a better solution than the accepted answer:
DateTime dateTime = DateFormat('dd-MM-yyyy h:mm:ssa', 'en_US').parseLoose('01-11-2020 2:00:00AM');
You can use Extension Methods with dart to extend existing libraries.
First define your extension , by extending the DateTime Object:
extension DateTimeExt on DateTime {
DateTime applyTimeOfDay({required int hour, required int minute}) {
return DateTime(year, month, day, hour, minute);
}
}
Once your new method is defined, you can call it exactly like the already defined methods of that object.
in this case, once you defined the applyTimeOfDay() method you can call it like so :
int myNewHour = 10
int myNewMinute = 8
var time = DateTime.parse("2018-08-16T11:00:00.000Z");
time = time.applyTimeOfDay(hour : myNewHour, minute : myNewMinute);
You can remove the current hours and minutes, and then add your wanted hours and minutes.
So if you would want to set the time to for example 23:59 you could do this:
final date = DateTime.now();
date
..subtract(Duration(hours: date.hour, minutes: date.minute))
..add(Duration(hours: 23, minutes: 59));
(Note that the other time units like seconds and milliseconds aren't changed here)
You can also do this by adding or subtracting to DateTime, using this package Jiffy. It also respects leap years and how many days are in each month
var updateTime = Jiffy("2018-08-16T11:00:00.000Z").add(hours: 1); // 2018-08-16 12:00:00.000Z
print(updateTime.dateTime); // 2018-08-16 12:30:00.000Z
// also you can format it
print(updateTime.format("yyyy, MMM")); // 2018, Aug
// or use default formats
print(updateTime.yMMMEdjm); // Thu, Aug 16, 2018 12:30 PM
I had some issues while using the formatted form of a DateTime object (using DateFormat) in my widget because showDatePicker brought a new instance of DateTime and calling setState doesn't have effect on the view.
There might be better ways to comply with my problem, but I decided to create my own one which is updateable using .update method.
import 'package:flutter/material.dart';
class MDateTime {
int year, month, day, hour, min, sec;
factory MDateTime.fromDateTime(DateTime dateTime) {
return MDateTime(
dateTime.year,
dateTime.month,
dateTime.day,
dateTime.hour,
dateTime.minute,
dateTime.second,
);
}
MDateTime([
this.year = 0,
this.month = 0,
this.day = 0,
this.hour = 0,
this.min = 0,
this.sec = 0,
]);
void update({
int? newYear,
int? newMonth,
int? newDay,
int? newHour,
int? newMin,
int? newSec,
}) {
year = newYear ?? year;
month = newMonth ?? month;
day = newDay ?? day;
hour = newHour ?? hour;
min = newMin ?? min;
sec = newSec ?? sec;
}
DateTime toDateTime() {
return DateTime(year, month, day, hour, min, sec);
}
TimeOfDay toTimeOfDay() {
return TimeOfDay(hour :hour, minute: min);
}
String formatDate({String divider = "-"}){
return "$year$divider$month$divider$day";
}
String formatTime({String divider = ":"}){
return "$hour$divider$min$divider$sec";
}
}
Moreover, there is no need to use another package for date-time formatting.
var newHour = 5;
time = time.toLocal();
time = new DateTime(time.year, time.month, time.day, newHour, time.minute, time.second, time.millisecond, time.microsecond);

Categories

Resources