GWT converting current date to GMT - gwt

I am converting the current date to GMT time.
The result is in-consistent, due to this my date time calculations are going worng.
DateTimeFormat df = DateTimeFormat.getFormat("dd MMM yyyy hh:mm:ss");
String gmtStr = new Date().toGMTString().replace("GMT", "").trim();
long deptime= depTime - df.parse(gmtStr).getTime();
deptime = deptime / 1000;
seconds = (deptime % 60);
minutes = (deptime % 3600) / 60;
hours = (deptime / 3600);

Not sure what the best way is, but you could use the getTimezoneOffsert:
final Date gmtDate = new Date();
final Date offDate = new Date(gmtDate.getTime() + gmtDate.getTimezoneOffset() * 60 * 1000);
The offDate when displayed with DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_LONG) will still show the utc/gmt offset, because basically you have create a new time in the current timezone, but it matches the time of the GMT time and the long value returned from getTime() will be the number of milliseconds you can use in your calculation.

Related

How to calculate Duration of Time between two date time through VBscript

How to calculate Duration of Time between two date time through VBscript
Date1 = 2021-01-22 11:43:38.000
Date2 = 2021-01-22 14:32:38.000
result should be HH:MM:SS
TimeSerial and FormatDateTime return a date or time that will take the regional settings of the computer into account. On my European computer no AM extension is shown because we use the 24h time format.
An additional problem with TimeSerial is that it will overflow once there are more than 32767 seconds.
A different approach could be to calculate the values for hours, minutes and seconds separately. A possible solution could be:
secValue = DateDiff("s",Date1,Date2)
hours = secValue \ 3600
hh = hours
if hours < 10 then
hh = Right("0" & hours, 2)
end if
mm = Right("0" & (secValue - hours * 3600) \ 60, 2)
ss = Right("0" & secValue mod 60, 2)
diff = hh & ":" & mm & ":" & ss
wscript.echo diff
Finally i answered to my Question Feeling great
Date1 = alA_Filling(0)
Date2 = alA_Filling(1)
secValue = DateDiff("s",Date1,Date2)
ts = TimeSerial(0, 0, secValue)
Duration = FormatDateTime(ts, vbLongTime)
But i got output like 2:49:00 AM why added AM to this may be this vbLongTime
how can i remove that AM

Date to Excel timestamp

I need to calculate an Excel "timestamp" (reference 01.01.1900, not 1970 like the unix timestamp) ; here what I did:
Date mydate = new Date();
unixTimestamp = mydate.getTime() / 1000;
excelTimestamp = unixTimestamp / 86400;
def startPoint= new GregorianCalendar(1900, Calendar.JANUARY, 0, 0,0,0).time;
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
howmany = tz.getOffset(new Date().getTime()) / 1000;
excelTimeStamp = (unixTimestamp - startPoint.time/1000) / 86400;
the latter returns 1 day less, and 1 hour more... what did I wrong ?
the solution was MUCH easier:
Date mydate = new Date();
unixTimestamp = mydate.getTime() / 1000;
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
howmany = tz.getOffset(new Date().getTime()) / 1000;
excelTimeStamp = 25569 + (unixTimestamp+howmany)/86400;

Flutter: Find the number of days between two dates

I currently have a user's profile page that brings out their date of birth and other details. But I am planning to find the days before their birthday by calculating the difference between today's date and the date of birth obtained from the user.
User's Date of Birth
And this is today's date obtained by using the intl package.
Today's date
I/flutter ( 5557): 09-10-2018
The problem I am facing now is, How do I calculate the difference in days of these two dates?
Are there any specific formulas or packages that are available for me to check out?
You can use the difference method provide by DateTime class
//the birthday's date
final birthday = DateTime(1967, 10, 12);
final date2 = DateTime.now();
final difference = date2.difference(birthday).inDays;
UPDATE
Since many of you reported there is a bug with this solution and to avoid more mistakes, I'll add here the correct solution made by #MarcG, all the credits to him.
int daysBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
//the birthday's date
final birthday = DateTime(1967, 10, 12);
final date2 = DateTime.now();
final difference = daysBetween(birthday, date2);
This is the original answer with full explanation: https://stackoverflow.com/a/67679455/666221
The accepted answer is wrong. Don't use it.
This is correct:
int daysBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
Testing:
DateTime date1 = DateTime.parse("2020-01-09 23:00:00.299871");
DateTime date2 = DateTime.parse("2020-01-10 00:00:00.299871");
expect(daysBetween(date1, date2), 1); // Works!
Explanation why the accepted answer is wrong:
Just run this:
int daysBetween_wrong1(DateTime date1, DateTime date2) {
return date1.difference(date2).inDays;
}
DateTime date1 = DateTime.parse("2020-01-09 23:00:00.299871");
DateTime date2 = DateTime.parse("2020-01-10 00:00:00.299871");
// Should return 1, but returns 0.
expect(daysBetween_wrong1(date1, date2), 0);
Note: Because of daylight savings, you can have a 23 hours difference between some day and the next day, even if you normalize to 0:00. That's why the following is ALSO incorrect:
// Fails, for example, when date2 was moved 1 hour before because of daylight savings.
int daysBetween_wrong2(DateTime date1, DateTime date2) {
from = DateTime(date1.year, date1.month, date1.day);
to = DateTime(date2.year, date2.month, date2.day);
return date2.difference(date1).inDays;
}
Rant: If you ask me, Dart DateTime is very bad. It should at least have basic stuff like daysBetween and also timezone treatment etc.
Update: The package https://pub.dev/packages/time_machine claims to be a port of Noda Time. If that's the case, and it's ported correctly (I haven't tested it yet) then that's the Date/Time package you should probably use.
Use DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
or
You can use jiffy. Jiffy is a date dart package inspired by momentjs for parsing, manipulating and formatting dates.
Example:
1. Relative Time
Jiffy("2011-10-31", "yyyy-MM-dd").fromNow(); // 8 years ago
Jiffy("2012-06-20").fromNow(); // 7 years ago
var jiffy1 = Jiffy()
..startOf(Units.DAY);
jiffy1.fromNow(); // 19 hours ago
var jiffy2 = Jiffy()
..endOf(Units.DAY);
jiffy2.fromNow(); // in 5 hours
var jiffy3 = Jiffy()
..startOf(Units.HOUR);
jiffy3.fromNow();
2. Date Manipulation:
var jiffy1 = Jiffy()
..add(duration: Duration(days: 1));
jiffy1.yMMMMd; // October 20, 2019
var jiffy2 = Jiffy()
..subtract(days: 1);
jiffy2.yMMMMd; // October 18, 2019
// You can chain methods by using Dart method cascading
var jiffy3 = Jiffy()
..add(hours: 3, days: 1)
..subtract(minutes: 30, months: 1);
jiffy3.yMMMMEEEEdjm; // Friday, September 20, 2019 9:50 PM
var jiffy4 = Jiffy()
..add(duration: Duration(days: 1, hours: 3))
..subtract(duration: Duration(minutes: 30));
jiffy4.format("dd/MM/yyy"); // 20/10/2019
// Months and year are added in respect to how many
// days there are in a months and if is a year is a leap year
Jiffy("2010/1/31", "yyyy-MM-dd"); // This is January 31
Jiffy([2010, 1, 31]).add(months: 1); // This is February 28
You can Use the Datetime class to find the difference between the two years without using intl to format the date.
DateTime dob = DateTime.parse('1967-10-12');
Duration dur = DateTime.now().difference(dob);
String differenceInYears = (dur.inDays/365).floor().toString();
return new Text(differenceInYears + ' years');
Naively subtracting one DateTime from another with DateTime.difference is subtly wrong. As explained by the DateTime documentation:
The difference between two dates in different time zones is just the number of nanoseconds between the two points in time. It doesn't take calendar days into account. That means that the difference between two midnights in local time may be less than 24 hours times the number of days between them, if there is a daylight saving change in between.
Instead of rounding the computed number of days, you can ignore Daylight Saving Time in DateTime calculations by using UTC DateTime objects1 because UTC does not observe DST.
Therefore, to compute the difference in days between two dates, ignoring the time (and also ignoring Daylight Saving adjustments and time zones), construct new UTC DateTime objects with the same dates and that use the same time of day:
/// Returns the number of calendar days between [later] and [earlier], ignoring
/// time of day.
///
/// Returns a positive number if [later] occurs after [earlier].
int differenceInCalendarDays(DateTime later, DateTime earlier) {
// Normalize [DateTime] objects to UTC and to discard time information.
later = DateTime.utc(later.year, later.month, later.day);
earlier = DateTime.utc(earlier.year, earlier.month, earlier.day);
return later.difference(earlier).inDays;
}
Update
I've added a calendarDaysTill extension method to package:basics that can do this.
1 Be aware that converting a local DateTime object to UTC with .toUtc() will not help; dateTime and dateTime.toUtc() both represent the same moment in time, so dateTime1.difference(dateTime2) and dateTime1.toUtc().difference(dateTime.toUtc()) would return the same Duration.
If anyone wants to find out the difference in form of seconds, minutes, hours, and days. Then here is my approach.
static String calculateTimeDifferenceBetween(
{#required DateTime startDate, #required DateTime endDate}) {
int seconds = endDate.difference(startDate).inSeconds;
if (seconds < 60)
return '$seconds second';
else if (seconds >= 60 && seconds < 3600)
return '${startDate.difference(endDate).inMinutes.abs()} minute';
else if (seconds >= 3600 && seconds < 86400)
return '${startDate.difference(endDate).inHours} hour';
else
return '${startDate.difference(endDate).inDays} day';
}
Beware of future "bugs" with selected answer
Something really missing in the selected answer - massively upvoted oddly - is that it will calculate the difference between two dates in term of:
Duration
It means that if there is less than 24h of differences both dates will be considered to be the same!! Often it is not the desired behavior. You can fix this by tweaking slightly the code in order to truncate from the day the clock:
Datetime from = DateTime(1987, 07, 11); // this one does not need to be converted, in this specific example, but we assume that the time was included in the datetime.
Datetime to = DateTime.now();
print(daysElapsedSince(from, to));
[...]
int daysElapsedSince(DateTime from, DateTime to) {
// get the difference in term of days, and not just a 24h difference
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return to.difference(from).inDays;
}
You can hence detect if from was before to, as it will return a positive integer representing the difference in term of number of days, else negative, and 0 if both happened on same day.
It is indicated in the documentation what this function return and in many usecases it can lead to some problem that may be difficult to debug if following the original selected answer:
Returns a Duration with the difference when subtracting other (from) from this (to).
Hope it helps.
void main() {
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-09-12 10:57:00");
Duration diff = dt1.difference(dt2);
print(diff.inDays);
//output (in days): 1198
print(diff.inHours);
//output (in hours): 28752
}
Simplest solution:
// d2.difference(d1).inDays
void main() {
final d1 = DateTime.now();
final d2 = d1.add(Duration(days: 2));
print(d2.difference(d1).inDays);
}
Check it out on DartPad example
Another and maybe more intuitive option is to use Basics package:
// the birthday's date
final birthday = DateTime(1967, 10, 12);
final today = DateTime.now();
final difference = (today - birthday).inDays;
For more information about the package: https://pub.dev/packages/basics
All of these answers miss a crucial part and that is leap year.
Here is the perfect solution for calculating age:
calculateAge(DateTime birthDate) {
DateTime currentDate = DateTime.now();
int age = currentDate.year - birthDate.year;
int month1 = currentDate.month;
int month2 = birthDate.month;
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = currentDate.day;
int day2 = birthDate.day;
if (day2 > day1) {
age--;
}
}
return age;
}
The above answers are also correct, I just create a single method to find out the difference between the two days, accepted for the current day.
void differenceBetweenDays() {
final date1 = DateTime(2022, 01, 01); // 01 jan 2022
final date2 = DateTime(2022, 02, 01); // 01 feb 2022
final currentDay = DateTime.now(); // Current date
final differenceFormTwoDates = daysDifferenceBetween(date1, date2);
final differenceFormCurrent = daysDifferenceBetween(date1, currentDay);
print("difference From date1 and date 2 :- "+differenceFormTwoDates.toString()+" "+"Days");
print("difference From date1 and Today :- "+differenceFormCurrent.toString()+" "+"Days");
}
int daysDifferenceBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
var start_date = "${DateTime.now()}";
var fulldate =start_date.split(" ")[0].split("-");
var year1 = int.parse(fulldate[0]);
var mon1 = int.parse(fulldate[1]);
var day1 = int.parse(fulldate[2]);
var date1 = (DateTime(year1,mon1,day1).millisecondsSinceEpoch);
var date2 = DateTime(2021,05,2).millisecondsSinceEpoch;
var Difference_In_Time = date2 - date1;
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
print(Difference_In_Days); ```
Extension on DateTime
With an extension class you could:
int days = birthdate.daysSince;
Example extension class:
extension DateTimeExt on DateTime {
int get daysSince => this.difference(DateTime.now()).inDays;
}

Date difference in hours - Angular 2

How can I get difference in hours between two dates in angular2? I don't want to use external libs like moment.js.
Having, for example: incidentTime = '2017-03-05 11:26:16 AM' and creationTime = '2017-03-06 12:26:16 AM'
let time = +params.data.incidentTime - +params.data.creationTime;
console.log("time: " + time);
It should return 25 hours, but It returns NaN.
This should do the job:
const date1 = params.data.incidentTime;
const date2 = params.data.creationTime;
const diffInMs = Date.parse(date2) - Date.parse(date1);
const diffInHours = diffInMs / 1000 / 60 / 60;
console.log(diffInHours);
Use Math.floor to round the result down, or Math.ceil to round it up
parse the date type parameters to javascript's Date type.
let date1 = new Date(params.data.incidentTime).getTime();
let date2 = new Date(params.data.creationTime).getTime();
let time = date1 - date2; //msec
let hoursDiff = time / (3600 * 1000);
Try this:-
let time:any = new Date("2017-03-05 11:26:16").getHours();
let date2:any = new Date("2017-03-06 12:26:16").getHours();
console.log(time -date2, time, date2, "sdfsd");
but It returns NaN
this is because you are using + sign before date which is converting youtr date into number format so returning NAN(not a number)

UIDatePicker - Difference between 2 dates in hours:minutes

I have this
NSDate *date1Val = date1.date;
NSDate *date2Val = date2.date;
NSTimeInterval interval = [date2Val timeIntervalSinceDate:date1Val];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:#"%d:%d", hours, minutes];
but it doesnt show me correct date - for 24 hours it says 23:57 no idea why
When selecting a date using a UIDatePicker in date only mode the time that was set in date + time mode is also present in the supplied date. You can go into IB, switch the UIDatePickers to Date & Time mode and make sure that the hour and minute are the same.