Format date into a month count and years - flutter

We have a DateTime value returning from JSON its coming thru as "10/9/2016 4:46:48 PM" .
What we need to do with it is format it to months or years past like so:
10/9/2016 = 3 years in the past.
The value 10/20/2019 = 3 months
Is this possible?
I'm guessing we would need to grab the month and year and subtract from today's date.

So I would create a function which will calculate difference between today's date and DateTime passed to it. It would look like this
String calculateDifference(DateTime dateTime) {
String text = "months";
double difference = DateTime.now().difference(dateTime).inDays / 30;
if (difference > 11) {
difference = difference / 12;
text = "years";
}
return "${difference.toStringAsFixed(0)} $text";
}
So you just need to parse the date from your JSON to DateTime object and pass it to a variable. You can also add one more condition to return value for days

You can use .difference on DateTime
final dateInThePast = DateTime(2018, 1, 7);
final dateNow = DateTime.now();
final difference = dateNow.difference(dateInThePast).inDays;
And then calculate from Days to Months / Years

Related

Parsing 24 HR Time to DateTime

I am attempting to convert the following 2HR time in String to a DateTime, so that I manage it appropriately.
"1800"
This question came close, but no one answered how to convert the String into a valid DateTime.
How to convert time stamp string from 24 hr format to 12 hr format in dart?
Attempt 1:
DateTime.parse("1800") -
Invalid Date Format
Attempt 2:
DateTime.ParseExact("1800") -
This doesn't seem to exist, although it shows up on various
Still no luck and need a second pair of eyes to point out the obvious to me.
The time by itself is not a datetime so you could do something like:
DateTime myTime(DateTime baseDate, String hhmm) {
assert(hhmm.length == 4, 'invalid time');
final _hours = int.parse(hhmm.substring(0, 2));
final _mins = int.parse(hhmm.substring(2, 2));
return DateTime(baseDate.year, baseDate.month, baseDate.day, _hours, _mins);
}
DateTime.parse expects to parse dates with times, not just times. (You can't even create a DateTime object without a date!)
Some people generate a dummy date string, but in your case you could trivially parse it with int.parse and then apply appropriate division and remainder operations:
var rawTime = int.parse('1800');
var hour = rawTime ~/ 100;
var minute = rawTime % 100;
Also see How do I convert a date/time string to a DateTime object in Dart? for more general DateTime parsing.

Trying to create datetime index for monthly rainfall vector

I have a vector of data that is 564 elements long representing 1970/Jan rainfall, 1970/feb rainfall etc.
I want to index the vector using datetime.
I've tried to create a datetime array like this
years = linspace(1970,2015,47);
years = repelem(years,12)';
months = [1:12];
months = repmat(months,1,47)';
day = 1;
datetime = datetime(years,months,day)
But this gives me the error -
"Error using datetime (line 581)
Year, month, day, hour, and minute components must be integer values.
Error in Station_plots (line 32)
datetime = datetime(years,months,day)".
Am I going about solving this problem correctly?
Try 46 instead of 47. Simple Math

How to work with date in Unity c#? [duplicate]

This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 4 years ago.
I create a game in unity. And I add a 'buy subscribe' (apple).
After click buy, I get Date (for example: 08/02/2018 07:24:23) 08 - is month, 02 - is date.
I get a date through this code:
productReceipt.subscriptionExpirationDate
Now i need to do a check, if CurrentDay - 08/02/2018 07:24:23 = 15 days;
How to calculate 2 dates?
You can do it using DateTime function. DateTime function allows you to calculate the number of days. You just need to get current datetime & parse your string to datetime format. Here is the code.
DateTime dateCurrent = DateTime.Now;
DateTime dateNext = DateTime.Parse(date);
int days = (dateNext - dateCurrent).Days;
Update:
You can also use TotalDays function to give the remaining time in fraction also. TotalDays is double so remember to change the days to double when using it.

How to convert fractional years (say 1.25 years) to number of days

I have a table that shows periods like 1 year to 10 years. I want to calculate number of days (approximately 365 days in a year and no need to include leap year). If it was just years, it is easy to calculate days ( like 2 years = 2*365 days). But how can convert for 1.5 years or 1.75 years into days?
what is the efficient way to calculate days if the years are specified in terms of fractional years.
Thanks
nath
Try:
float year = 1.5;
int days = Math.Round(year * 365);
Since the original question is trivial, I'll answer the more interesting question where leap years and other date/time oddities are to be considered. Since the exact number of days in a year is dependent on the year in question, the only sensible approach would be to calculate it relative to a given date. The first step would be an AddYears overload that accepts double values:
public static DateTime AddYears(this DateTime dateTime, double years)
{
int roundedYears = (int) Math.Floor(years);
var roundedDate = dateTime.AddYears(roundedYears);
var lastYearSpan = roundedDate.AddYears(1) - roundedDate;
return roundedDate.AddDays((years % 1) * lastYearSpan.TotalDays);
}
Now you can get the number of days that make sense for you, for example:
var now = DateTime.UtcNow;
Console.WriteLine((now.AddYears(1.25) - now).TotalDays);
Sample tests:
public void TestAddYearsDouble()
{
var date = new DateTime(2000, 1, 15); //middle of the month to keep things simple
Assert.AreEqual(date.Year + 1, date.AddYears(1.0).Year);
Assert.AreEqual(date.Month, date.AddYears(1.0).Month);
Assert.AreEqual(date.Year, date.AddYears(0.0833).Year);
Assert.AreEqual(date.Month + 1, date.AddYears(0.0833).Month);
Assert.AreEqual(date.Year + 8, date.AddYears(8.5).Year);
Assert.AreEqual(date.Month + 6, date.AddYears(8.5).Month);
}

Given Year, Month,Day and the Week number, is it possible to get the Date in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date from week number
Given Year, Month,Day and the Week number, is it possible to get the Date?
e.g. Year = 2010
Month =Jan
Day = Sun
WeekNumber = 3
output : 2010-01-10
I am trying it in c#
Thanks
I would make it like this:
int Year = 2010;
int Month = 1; //Jan=1, Feb=2, ...
int Day = 0; //Sun=0, Mon=1, ...
int WeekNumber = 3; // greater than 0
DateTime dateValue = new DateTime(Year, Month, 1);
int firstDay = (int)dateValue.DayOfWeek;
dateValue = dateValue.AddDays(Day - firstDay + (WeekNumber - 1) * 7);
I don't think there's something for such date calculations in plain .NET BCL. But there are libraries that can help you, see i.e. Fluent DateTime. Using this library, you can try something like that:
var firstWeekInYearBeginning = new DateTime(2010, 1, 2).Previous(DayOfWeek.Monday); // note 2 to not miss a week if the year begins on Monday
var expectedDate = 3.Weeks().From(firstWeekInYearBeginning);
Based on the APIs here, don't this its possible to initialize a DateTime Object from the information given. You would need to develop an algorithm to get the exact date of the year. A simple strategy would be to get the first Day of the month and based on that, find first Monday of the month. This is the start of WeekNumber 1 for that month, and you can locate your required Week by simpl loop and locate the exact date. You would then know the calendar date you are interested in.
BTW: I am assuming WeekNumber of a year/month starts from the first Monday of that Year/Month. Someone please correct me if I am wrong.
Maybe you should check out System.Globalization.Calendar class. It might be useful.