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);
Related
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"
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
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
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);
I am new to Android.I have a requirement, I have a field to enter the Date Of Birth of a person.On successful selection I wanna return the total number of months from the DOB to current date.For example, if I entered DOB as 19/10/2012 I wanna return 36(months).I searched for this, but didn't find anything suitable to my requirement.Here is my current code which return sucessful data,
private void showDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day);
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if(System.currentTimeMillis() > date.getTime()) {
edtDate.setText(sdf.format(date));
LocalDate date1 = new LocalDate(date);
LocalDate date2 = new LocalDate(new java.util.Date());
PeriodType monthDay = PeriodType.yearMonthDayTime();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
months=months + 1;
System.out.println("16102015:Nunber of Months"+months);
}else{
Toast.makeText(mActivity,getResources().getString(R.string.date_validationmsg),Toast.LENGTH_LONG).show();
}
}
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
To start with, I'd suggest using LocalDate instead of DateTime for the computations. Ideally, don't use java.util.Date at all, and take your input as LocalDate to start with (e.g. by parsing text straight to that, or wherever your data comes from.) Set the day of month to 1 in both dates, and then take the difference in months:
private static int monthsBetweenDates(LocalDate start, LocalDate end) {
start = start.withDayOfMonth(1);
end = end.withDayOfMonth(1);
return Months.monthsBetween(start, end).getMonths();
}
UPDATE 1
see this link the OP is accepted the same answer because Months.monthsBetween() method is not working proper for him
UPDATE 2
LocalDate userEnteredDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date));
LocaleDate currentDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
int months = monthsBetweenDates(userEnteredDate, currentDate)
Using Joda-time library here, I was able to get the desired result.
Try the below code it would give the desired the difference in months.
DateTime date1 = new DateTime().withDate(2012, 10, 19);
DateTime today = new DateTime().withDate(2015, 10, 19);
// calculate month difference
int diffMonths = Months.monthsBetween(date1.withDayOfMonth(1), today.withDayOfMonth(1)).getMonths();
Using JodaTime, it's really easy:
http://www.joda.org/joda-time/apidocs/
int nMonths = new Period(startTime, endTime).getMonths();
Use this code to calculate months between two dates
public static int monthsBetweenUsingJoda(Date d1, Date d2) {
return Months.monthsBetween(new LocalDate(d1.getTime()), new LocalDate(d2.getTime())).getMonths();
}