Monty  Boehm

Monty Boehm

1670933659

The Definitive Guide to DateTime Manipulation

Time and date manipulation is notoriously difficult. Developers encountering time zone rules, leap seconds, differences in locale-specific formatting are wise to resort to popular time and date manipulation libraries. But without thinking about how exactly they work, it’s still easy to create all sorts of obscure bugs.

As a software developer, you can’t run away from date manipulation. Almost every app a developer builds will have some component where date/time needs to be obtained from the user, stored in a database, and displayed back to the user.

Ask any programmer about their experience handling dates and time zones and they will probably share some war stories. Handling date and time fields is certainly not rocket science but can often be tedious and error-prone.

There are hundreds of articles on the topic out there, however, most are either too academic, focusing on nitty-gritty details, or they are too patchy, providing short snippets of code without much explanation accompanying them. This in-depth guide to DateTime manipulation should help you understand the programming concepts and best practices relevant to time and date without having to browse through a sea of information on this topic.

In this article, I’m going to help you think clearly about date and time fields and suggest some best practices that can help you avoid date/time hell. Here we will explore some of the key concepts that are necessary for manipulating date and time values correctly, formats that are convenient for storing DateTime values and transferring them over APIs, and more.

For starters, the right answer for production code is almost always to use a proper library rather than rolling your own. The potential difficulties with DateTime calculation discussed in this article are only the tip of the iceberg, but they’re still helpful to know about, with or without a library.

DateTime Libraries Help If You Understand Them Correctly

Date libraries help in many ways to make your life easier. They greatly simplify date parsing, date arithmetic and logical operations, and date formatting. You can find a reliable date library for both the front end and the back end to do most of the heavy lifting for you.

However, we often use date libraries without thinking about how date/time actually works. Date/time is a complex concept. The bugs that come up due to its incorrect understanding can be extremely difficult to understand and fix, even with the help of date libraries. As a programmer, you need to understand the basics and be able to appreciate the problems that date libraries solve to make the most out of them.

Also, date/time libraries can only take you so far. All date libraries work by giving you access to convenient data structures to represent a DateTime. If you are sending and receiving data through a REST API, you will eventually need to convert the date to a string and vice versa because JSON doesn’t have a native data structure to represent DateTime. The concepts I have outlined here will help you to avoid some of the common issues that might come up when doing these date-to-string and string-to-date transformations.

Note: Even though I have used JavaScript as the programming language discussed in this article, these are general concepts that apply, to a large extent, to virtually all programming languages and their date libraries. So even if you’ve never written a line of JavaScript before, feel free to continue reading as I hardly assume any prior knowledge of JavaScript in the article.

Standardizing the Time

A DateTime is a very specific point in time. Let’s think about this. As I scribble this article, the clock on my laptop shows July 21 1:29 PM. This is what we call “local time,” the time that I see on wall clocks around me and on my wrist watch.

Give or take a few minutes, if I ask my friend to meet me at a nearby cafe at 3:00 PM, I can expect to see her there at roughly that time. Similarly, there wouldn’t be any confusion if instead I said, for example, “let’s meet in one and a half hours.” We routinely talk about time this way with people living in the same city or time zone.

Let’s think of a different scenario: I want to tell a friend living in Uppsala, Sweden that I want to talk to him at 5 PM. I send him a message, “Hey Anton, let’s talk at 5 PM.” I immediately get the response, “Your time or my time?”

Anton tells me that he lives in the Central European time zone which is UTC+01:00. I live in UTC+05:45. This means that when it is 5 PM where I live, it is 5 PM - 05:45 = 11:15 AM UTC, which translates to 11:15 AM UTC + 01:00 = 12:15 PM in Uppsala, perfect for both of us.

Also, be aware of the difference between time zone (Central European Time) and time zone offset (UTC+05:45). Countries can decide to change their time zone offsets for Daylight Savings Time for political reasons as well. Almost every year there’s a change to the rules in at least one country, meaning any code with these rules baked in must be kept up-to-date—it’s worth considering what your codebase depends on for this for each tier of your app.

That’s another good reason we’ll recommend that only the front end deals with time zones in most cases. When it doesn’t, what happens when the rules your database engine uses don’t match those of your front or back end?

This problem of managing two different versions of the time, relative to the user and relative to a universally accepted standard, is difficult, even more so in the world of programming where precision is key and even one second can make a huge difference. The first step towards solving these issues is to store DateTime in UTC.

Standardizing the Format

Standardizing the time is wonderful because I only need to store the UTC time and as long as I know the time zone of the user, I can always convert to their time. Conversely, if I know a user’s local time and know their time zone, I can convert that to UTC.

But dates and times can be specified in many different formats. For the date, you could write “Jul 30th” or “30 July” or “7/30” (or 30/7, depending on where you live). For the time, you could write “9:30 PM” or “2130”.

Scientists all over the world came together to tackle this problem and decided on a format to describe time that programmers really like because it’s short and precise. We like to call it “ISO date format,” which is a simplified version of the ISO-8601 extended format and it looks like this:

 

An image showing a simplified version of the ISO-8601 extended format called the ISO date format.

 

For 00:00 or UTC, we use “Z” instead, which means Zulu time, another name for UTC.

Date Manipulation and Arithmetic in JavaScript

Before we start with best practices, we will learn about date manipulation using JavaScript to get a grasp of the syntax and general concepts. Although we use JavaScript, you can adapt this information to your favorite programming language easily.

We will use date arithmetic to solve common date-related problems that most developers come across.

My goal is to make you comfortable creating a date object from a string and extracting components out of one. This is something that a date library can help you with, but it’s always better to understand how it is done behind the scenes.

Once we’ve gotten our hands dirty with date/time, it is then easier to think about the problems we face, extract the best practices, and move ahead. If you want to skip to the best practices, feel free to do so, but I would highly recommend you to at least skim through the date-arithmetic section below.

The JavaScript Date Object

Programming languages contain useful constructs to make our lives easier. The JavaScript Date object is one such thing. It offers convenient methods to get the current date and time, store a date in a variable, perform date arithmetic, and format the date based on the user’s locale.

Due to differences between browser implementations and incorrect handling of Daylight Savings Time (DST), depending on the Date object for mission-critical applications is not recommended and you should probably be using a DateTime library like Luxon, date-fns, or dayjs. (Whatever you use, avoid the once-popular Moment.js—often simply called moment, as it appears in code—since it’s now deprecated.)

But for educational purposes, we will use the methods that the Date() object provides to learn how JavaScript handles DateTime.

Getting Current Date

const currentDate = new Date();

If you don’t pass anything to the Date constructor, the date object returned contains the current date and time.

You can then format it to extract only the date part as follows:

const currentDate = new Date();

const currentDayOfMonth = currentDate.getDate();
const currentMonth = currentDate.getMonth(); // Be careful! January is 0, not 1
const currentYear = currentDate.getFullYear();

const dateString = currentDayOfMonth + "-" + (currentMonth + 1) + "-" + currentYear;
// "27-11-2020"

Note: The “January is 0” pitfall is common but not universal. It’s worth double-checking the documentation of any language (or configuration format: e.g., cron is notably 1-based) before you start using it.

Getting the Current Time Stamp

If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method.

const currentDate = new Date();
const timestamp = currentDate.getTime();

In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.

If you don’t intend to support <IE8, you can use Date.now() to directly get the time stamp without having to create a new Date object.

Parsing a Date

Converting a string to a JavaScript date object is done in different ways.

The Date object’s constructor accepts a wide variety of date formats:

const date1 = new Date("Wed, 27 July 2016 13:30:00");
const date2 = new Date("Wed, 27 July 2016 07:45:00 UTC");
const date3 = new Date("27 July 2016 13:30:00 UTC+05:45");

Note that you do not need to include the day of week because JS can determine the day of the week for any date.

You can also pass in the year, month, day, hours, minutes, and seconds as separate arguments:

const date = new Date(2016, 6, 27, 13, 30, 0);

Of course, you can always use ISO date format:

const date = new Date("2016-07-27T07:45:00Z");

However, you can run into trouble when you do not provide the time zone explicitly!

const date1 = new Date("25 July 2016");
const date2 = new Date("July 25, 2016");

Either of these will give you 25 July 2016 00:00:00 local time.

If you use the ISO format, even if you give only the date and not the time and time zone, it will automatically accept the time zone as UTC.

This means that:

new Date("25 July 2016").getTime() !== new Date("2016-07-25").getTime()
new Date("2016-07-25").getTime() === new Date("2016-07-25T00:00:00Z").getTime()

Formatting a Date

Fortunately, modern JavaScript has some convenient internationalization functions built into the standard Intl namespace that make date formatting a straightforward operation.

For this we’ll need two objects: a Date and an Intl.DateTimeFormat, initialized with our output preferences. Supposing we’d like to use the American (M/D/YYYY) format, this would look like:

const firstValentineOfTheDecade = new Date(2020, 1, 14); // 1 for February
const enUSFormatter = new Intl.DateTimeFormat('en-US');
console.log(enUSFormatter.format(firstValentineOfTheDecade));
// 2/14/2020

If instead we wanted the Dutch (D/M/YYYY) format, we would just pass a different culture code to the DateTimeFormat constructor:

const nlBEFormatter = new Intl.DateTimeFormat('nl-BE');
console.log(nlBEFormatter.format(firstValentineOfTheDecade));
// 14/2/2020

Or a longer form of the American format, with the month name spelled out:

const longEnUSFormatter = new Intl.DateTimeFormat('en-US', {
    year:  'numeric',
    month: 'long',
    day:   'numeric',
});
console.log(longEnUSFormatter.format(firstValentineOfTheDecade));
// February 14, 2020

Now, if we wanted a proper ordinal format on the day of the month—that is, “14th” instead of just “14”—this unfortunately needs a bit of a workaround, because day’s only valid values as of this writing are "numeric" or "2-digit". Borrowing Flavio Copes’ version of Mathias Bynens’ code to leverage another part of Intl for this, we can customize the day of the month output via formatToParts():

const pluralRules = new Intl.PluralRules('en-US', {
    type: 'ordinal'
})
const suffixes = {
    'one': 'st',
    'two': 'nd',
    'few': 'rd',
    'other': 'th'
}
const convertToOrdinal = (number) => `${number}${suffixes[pluralRules.select(number)]}`
// At this point:
// convertToOrdinal("1") === "1st"
// convertToOrdinal("2") === "2nd"
// etc.

const extractValueAndCustomizeDayOfMonth = (part) => {
    if (part.type === "day") {
        return convertToOrdinal(part.value);
    }
    return part.value;
};
console.log(
    longEnUSFormatter.formatToParts(firstValentineOfTheDecade)
    .map(extractValueAndCustomizeDayOfMonth)
    .join("")
);
// February 14th, 2020

Unfortunately, formatToParts isn’t supported by Internet Explorer (IE) at all as of this writing, but all other desktop, mobile, and back-end (i.e. Node.js) technologies do have support. For those who need to support IE and absolutely need ordinals, the sidenote below (or better, a proper date library) provides an answer.

If you need to support older browsers like IE before version 11, date formatting in JavaScript is tougher because there were no standard date-formatting functions like strftime in Python or PHP.

In PHP for example, the function strftime("Today is %b %d %Y %X", mktime(5,10,0,12,30,99)) gives you Today is Dec 30 1999 05:10:00.

You can use a different combination of letters preceded by % to get the date in different formats. (Careful, not every language assigns the same meaning to each letter—particularly, 'M' and 'm' may be swapped for minutes and months.)

If you are sure of the format you want to use, it is best to extract individual bits using the JavaScript functions we covered above and create a string yourself.

var currentDate = new Date();
var date = currentDate.getDate();
var month = currentDate.getMonth(); 
var year = currentDate.getFullYear();

We can get the date in MM/DD/YYYY format as

var monthDateYear  = (month+1) + "/" + date + "/" + year;

The problem with this solution is that it can give an inconsistent length to the dates because some months and days of the month are single-digit and others double-digit. This can be problematic, for example, if you are displaying the date in a table column, because the dates don’t line up.

We can address this by using a “pad” function that adds a leading 0.

function pad(n) {
    return n<10 ? '0'+n : n;
}

Now, we get the correct date in MM/DD/YYYY format using:

var mmddyyyy = pad(month + 1) + "/" + pad(date) + "/" + year;

If we want DD-MM-YYYY instead, the process is similar:

var ddmmyyyy = pad(date) + "-" + pad(month + 1) + "-" + year;

Let’s up the ante and try to print the date in “Month Date, Year” format. We will need a mapping of month indexes to names:

var monthNames = [
    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
];

var dateWithFullMonthName = monthNames[month] + " " + pad(date) + ", " + year;

Some people like to display the date as 1st January, 2013. No problem, all we need is a helper function ordinal that returns 1st for 1, 12th for 12, and 103rd for 103, etc., and the rest is simple:

var ordinalDate = ordinal(date) + " " + monthNames[month] + ", " + year;

It is easy to determine the day of week from the date object, so let’s add that in:

var daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];


ordinalDateWithDayOfWeek = daysOfWeek[currentDate.getDay()] + ", " + ordinalDate;

The bigger point here is, once you’ve got the numbers extracted from the date, the formatting is mostly related to strings.

Changing the Date Format

Once you know how to parse a date and format it, changing a date from one format to another is just a matter of combining the two.

For example, if you have a date in the format Jul 21, 2013 and wanted to change the format to 21-07-2013, it can be achieved like this:

const myDate = new Date("Jul 21, 2013");
const dayOfMonth = myDate.getDate();
const month = myDate.getMonth();
const year = myDate.getFullYear();

function pad(n) {
    return n<10 ? '0'+n : n
}

const ddmmyyyy = pad(dayOfMonth) + "-" + pad(month + 1) + "-" + year;
// "21-07-2013"

Using JavaScript Date Object’s Localization Functions

The date formatting methods we discussed above should work in most applications, but if you really want to localize the formatting of the date, I suggest you use the Date object’s toLocaleDateString() method:

const today = new Date().toLocaleDateString('en-GB', {  
    day:   'numeric',
    month: 'short',
    year:  'numeric',
});

…gives us something like 26 Jul 2016.

Changing the locale to ‘en-US’ gives “Jul 26, 2016” instead. Notice how the formatting changed, but the display options were still kept the same—a very useful feature. As shown in the previous section, the newer Intl.DateTimeFormat-based technique works very similarly to this, but lets you reuse a formatter object so that you only need to set options once.

With toLocaleDateString(), it is a good habit to always pass the formatting options, even if the output looks fine on your computer. This can protect the UI from breaking in unexpected locales with really long month names or looking awkward because of short ones.

If I wanted the full month “July” instead, all I do is change the month parameter in the options to “long”. JavaScript handles everything for me. For en-US, I now get July 26, 2016.

Note: If you want the browser to automatically use the user’s locale, you can pass “undefined” as the first parameter.

If you want to show the numeric version of the date and don’t want to fuss with MM/DD/YYYY vs. DD/MM/YYYY for different locales, I suggest the following simple solution:

const today = new Date().toLocaleDateString(undefined, {
    day:   'numeric',
    month: 'numeric',
    year:  'numeric',
});

On my computer, this outputs 7/26/2016. If you want to make sure that month and date have two digits, just change the options:

const today = new Date().toLocaleDateString(undefined, {
    day:   '2-digit',
    month: '2-digit',
    year:  'numeric',
});

This outputs 07/26/2016. Just what we wanted!

You can also use some other related functions to localize the way both time and date are displayed:

CodeOutputDescription
now.toLocaleTimeString()
"4:21:38 AM"Display localized version of only time
now.toLocaleTimeString(undefined, {
    hour:   '2-digit',
    minute: '2-digit',
    second: '2-digit',
});
"04:21:38 AM"Display localized time based on options provided
now.toLocaleString()
"7/22/2016, 4:21:38 AM"Display date and time for user's locale
now.toLocaleString(undefined, {
    day:    'numeric',
    month:  'numeric',
    year:   'numeric',
    hour:   '2-digit',
    minute: '2-digit',
});
"7/22/2016, 04:21 AM"Display localized date and time based on options provided

Calculating Relative Dates and Times

Here’s an example of adding 20 days to a JavaScript Date (i.e., figuring out the date 20 days after a known date):

const myDate = new Date("July 20, 2016 15:00:00");
const nextDayOfMonth = myDate.getDate() + 20;
myDate.setDate(nextDayOfMonth);
const newDate = myDate.toLocaleString();

The original date object now represents a date 20 days after July 20 and newDate contains a localized string representing that date. On my browser, newDate contains “8/9/2016, 3:00:00 PM”.

To calculate relative time stamps with a more precise difference than whole days, you can use Date.getTime() and Date.setTime() to work with integers representing the number of milliseconds since a certain epoch—namely, January 1, 1970. For example, if you want to know when it’s 17 hours after right now:

const msSinceEpoch = (new Date()).getTime();
const seventeenHoursLater = new Date(msSinceEpoch + 17 * 60 * 60 * 1000);

Comparing Dates

As with everything else related to date, comparing dates has its own gotchas.

First, we need to create date objects. Fortunately, <, >, <=, and >= all work. So comparing July 19, 2014 and July 18, 2014 is as easy as:

const date1 = new Date("July 19, 2014");
const date2 = new Date("July 28, 2014");

if(date1 > date2) {
    console.log("First date is more recent");
} else {
    console.log("Second date is more recent");
}

Checking for equality is trickier, since two date objects representing the same date are still two different date objects and will not be equal. Comparing date strings is a bad idea because, for example, “July 20, 2014” and “20 July 2014” represent the same date but have different string representations. The snippet below illustrates the first point:

const date1 = new Date("June 10, 2003");
const date2 = new Date(date1);

const equalOrNot = date1 == date2 ? "equal" : "not equal";
console.log(equalOrNot);

This will output not equal.

This particular case can be fixed by comparing the integer equivalents of the dates (their time stamps) as follows:

date1.getTime() == date2.getTime()

I’ve seen this example in lots of places, but I don’t like it because you don’t create a date object from another date object usually. So I feel that the example is important from an academic point of view only. Also, this requires both Date objects to be referring to the exact same second, whereas you might only want to know if they refer to the same day or hour or minute.

Let’s look at a more practical example. You’re trying to compare whether the birthday the user has entered is the same as the lucky date you are getting from an API.

const userEnteredString = "12/20/1989"; // MM/DD/YYYY format
const dateStringFromAPI = "1989-12-20T00:00:00Z";

const dateFromUserEnteredString = new Date(userEnteredString)
const dateFromAPIString = new Date(dateStringFromAPI);

if (dateFromUserEnteredString.getTime() == dateFromAPIString.getTime()) {
    transferOneMillionDollarsToUserAccount();
} else {
    doNothing();
}

Both represented the same date but unfortunately your user will not get the million dollars.

Here’s the problem: JavaScript always assumes the time zone to be the one that the browser provides it unless explicitly specified otherwise.

This means, for me, new Date ("12/20/1989") will create a date 1989-12-20T00:00:00+5:45 or 1989-12-19T18:15:00Z which is not the same as 1989-12-20T00:00:00Z in terms of time stamp.

It’s not possible to change just the time zone of an existing date object, so our target is now to create a new date object but with UTC instead of local time zone.

We will ignore the user’s time zone and use UTC while creating the date object. There are two ways to do it:

  1. Create an ISO formatted date string from the user input date and use it to create a Date object. Using a valid ISO date format to create a Date object while making the intent of UTC vs local very clear.
const userEnteredDate = "12/20/1989";
const parts = userEnteredDate.split("/");

const userEnteredDateISO = parts[2] + "-" + parts[0] + "-" + parts[1];

const userEnteredDateObj = new Date(userEnteredDateISO + "T00:00:00Z");
const dateFromAPI = new Date("1989-12-20T00:00:00Z");

const result = userEnteredDateObj.getTime() == dateFromAPI.getTime(); // true

This also works if you don’t specify the time since that will default to midnight (i.e., 00:00:00Z):

const userEnteredDate = new Date("1989-12-20");
const dateFromAPI = new Date("1989-12-20T00:00:00Z");
const result = userEnteredDate.getTime() == dateFromAPI.getTime(); // true

Remember: If the date constructor is passed a string in correct ISO date format of YYYY-MM-DD, it assumes UTC automatically.

  1. JavaScript provides a neat Date.UTC() function that you can use to get the UTC time stamp of a date. We extract the components from the date and pass them to the function.
const userEnteredDate = new Date("12/20/1989");
const userEnteredDateTimeStamp = Date.UTC(userEnteredDate.getFullYear(), userEnteredDate.getMonth(), userEnteredDate.getDate(), 0, 0, 0);

const dateFromAPI = new Date("1989-12-20T00:00:00Z");
const result = userEnteredDateTimeStamp == dateFromAPI.getTime(); // true
...

Finding the Difference Between Two Dates

A common scenario you will come across is to find the difference between two dates.

We discuss two use cases:

FINDING THE NUMBER OF DAYS BETWEEN TWO DATES

Convert both dates to UTC time stamp, find the difference in milliseconds and find the equivalent days.

const dateFromAPI = "2016-02-10T00:00:00Z";

const now = new Date();
const datefromAPITimeStamp = (new Date(dateFromAPI)).getTime();
const nowTimeStamp = now.getTime();

const microSecondsDiff = Math.abs(datefromAPITimeStamp - nowTimeStamp);

// Math.round is used instead of Math.floor to account for certain DST cases
// Number of milliseconds per day =
//   24 hrs/day * 60 minutes/hour * 60 seconds/minute * 1000 ms/second
const daysDiff = Math.round(microSecondsDiff / (1000 * 60 * 60  * 24));

console.log(daysDiff);

FINDING USER’S AGE FROM THEIR DATE OF BIRTH

const birthDateFromAPI = "12/10/1989";

Note: We have a non-standard format. Read the API doc to determine if this means 12 Oct or 10 Dec. Change to ISO format accordingly.

const parts = birthDateFromAPI.split("/");
const birthDateISO = parts[2] + "-" + parts[0] + "-" + parts[1];

const birthDate =  new Date(birthDateISO);
const today = new Date();

let age = today.getFullYear() - birthDate.getFullYear();

if(today.getMonth() < birthDate.getMonth()) {
    age--;
}

if(today.getMonth() == birthDate.getMonth() && today.getDate() < birthDate.getDate()) {
    age--;
}

I know there are more concise ways to write this code but I like to write it this way because of the sheer clarity of the logic.

Suggestions to Avoid Date Hell

Now that we are comfortable with date arithmetic, we are in a position to understand the best practices to follow and the reasons for following them.

Getting DateTime from User

If you are getting the date and time from the user, you are most probably looking for their local DateTime. We saw in the date arithmetic section that the Date constructor can accept the date in a number of different ways.

To remove any confusion, I always suggest creating a date using new Date(year, month, day, hours, minutes, seconds, milliseconds) format even if you already have the date in a valid parsable format. If all programmers in your team follow this simple rule, it will be extremely easy to maintain the code in the long run since it is as explicit as you can be with the Date constructor.

The cool part is that you can use the variations that allow you to omit any of the last four parameters if they are zero; i.e., new Date(2012, 10, 12) is the same as new Date(2012, 10, 12, 0, 0, 0, 0) because the unspecified parameters default to zero.

For example, if you are using a date and time picker that gives you the date 2012-10-12 and time 12:30, you can extract the parts and create a new Date object as follows:

const dateFromPicker = "2012-10-12";
const timeFromPicker = "12:30";

const dateParts = dateFromPicker.split("-");
const timeParts = timeFromPicker.split(":");
const localDate = new Date(dateParts[0], dateParts[1]-1, dateParts[2], timeParts[0], timeParts[1]);

Try to avoid creating a date from a string unless it is in ISO date format. Use the Date(year, month, date, hours, minutes, seconds, microseconds) method instead.

Getting Only the Date

If you are getting only the date, a user’s birthdate for instance, it is best to convert the format to valid ISO date format to eliminate any time zone information that can cause the date to shift forward or backward when converted to UTC. For example:

const dateFromPicker = "12/20/2012";
const dateParts = dateFromPicker.split("/");
const ISODate = dateParts[2] + "-" + dateParts[0] + "-" + dateParts[1];
const birthDate = new Date(ISODate).toISOString();

In case you forgot, if you create a Date object with the input in valid ISO date format (YYYY-MM-DD), it will default to UTC instead of defaulting to the browser’s time zone.

Storing the Date

Always store the DateTime in UTC. Always send an ISO date string or a time stamp to the back end.

Generations of computer programmers have realized this simple truth after bitter experiences trying to show the correct local time to the user. Storing the local time in the back end is a bad idea, it’s better to let the browser handle the conversion to local time in the front end.

Also, it should be apparent that you should never send a DateTime string like “July 20, 1989 12:10 PM” to the back end. Even if you send the time zone as well, you are increasing the effort for other programmers to understand your intentions and parse and store the date correctly.

Use the toISOString() or toJSON() methods of the Date object to convert the local DateTime to UTC.

const dateFromUI = "12-13-2012";
const timeFromUI = "10:20";
const dateParts = dateFromUI.split("-");
const timeParts = timeFromUI.split(":");

const date = new Date(dateParts[2], dateParts[0]-1, dateParts[1], timeParts[0], timeParts[1]);

const dateISO = date.toISOString();

$.post("http://example.com/", {date: dateISO}, ...)

Displaying the Date and Time

  1. Get the time stamp or the ISO formatted date from a REST API.
  2. Create a Date object.
  3. Use the toLocaleString() or toLocaleDateString() and toLocaleTimeString() methods or a date library to display the local time.
const dateFromAPI = "2016-01-02T12:30:00Z";

const localDate = new Date(dateFromAPI);
const localDateString = localDate.toLocaleDateString(undefined, {  
    day:   'numeric',
    month: 'short',
    year:  'numeric',
});


const localTimeString = localDate.toLocaleTimeString(undefined, {
    hour:   '2-digit',
    minute: '2-digit',
    second: '2-digit',
});

When Should You Store the Local Time Too?

“Sometimes it’s important to know the time zone in which an event occurred, and converting to a single time zone irrevocably obliterates that information.

“If you’re doing a marketing promotion and want to know which customers placed orders around lunchtime, an order that appears to have been placed at noon GMT isn’t very helpful when it was actually placed over breakfast in New York.”

If you come across this kind of situation, it would be wiser to save the local time as well. As usual, we would like to create the date in ISO format, but we have to find the time zone offset first.

The Date object’s getTimeZoneOffset() function tells us the number of minutes that when added to a given local time gives the equivalent UTC time. I suggest converting it to (+-)hh:mm format because it makes it more obvious that it is a time zone offset.

const now = new Date();
const tz = now.gettime zoneOffset();

For my time zone +05:45, I get -345, this is not only the opposite sign, but a number like -345 might be completely perplexing to a back-end developer. So we convert this to +05:45.

const sign = tz > 0 ? "-" : "+";

const hours = pad(Math.floor(Math.abs(tz)/60));
const minutes = pad(Math.abs(tz)%60);

const tzOffset = sign + hours + ":" + minutes;

Now we get the rest of the values and create a valid ISO string that represents the local DateTime.

const localDateTime = now.getFullYear() +
                      "-" +
                      pad(now.getMonth()+1) +
                      "-" +
                      pad(now.getDate()) +
                      "T" +
                      pad(now.getHours()) +
                      ":" +
                      pad(now.getMinutes()) +
                      ":" +
                      pad(now.getSeconds());

If you want, you can wrap the UTC and local dates in an object.

const eventDate = {
    utc: now.toISOString(),
    local: localDateTime,
    tzOffset: tzOffset,
}

Now, in the back end, if you wanted to find out if the event occurred before noon local time, you can parse the date and simply use the getHours() function.

const localDateString = eventDate.local;
const localDate = new Date(localDateString);

if(localDate.getHours() < 12) {
    console.log("Event happened before noon local time");
}

We didn’t use the tzOffset here, but we still store it because we might need it in the future for debugging purposes. You could actually just send the time zone offset and UTC time only. But I like to store the local time too because you will eventually have to store the date in a database and having the local time stored separately allows you to directly query based on a field rather than having to perform calculations to get the local date.

Sometimes, even with the local time zone stored, you’ll want to display dates in a particular time zone. For example, times for events might make more sense in the current user’s time zone if they’re virtual, or in the time zone where they will physically take place, if they’re not. In any case, it’s worth looking beforehand at established solutions for formatting with explicit time zone names.

Server and Database Configuration

Always configure your servers and databases to use UTC time zone. (Note that UTC and GMT are not the same thing—GMT, for example, might imply a switch to BST during the summer, whereas UTC never will.)

We have already seen how much of a pain time zone conversions can be, especially when they are unintended. Always sending UTC DateTime and configuring your servers to be in UTC time zone can make your life easier. Your back-end code will be much simpler and cleaner as it doesn’t have to do any time zone conversions. DateTime data coming in from servers across the world can be compared and sorted effortlessly.

Code in the back end should be able to assume the time zone of the server to be UTC (but should still have a check in place to be sure). A simple configuration check saves having to think about and code for conversions every time new DateTime code is written.

It’s Time for Better Date Handling

Date manipulation is a hard problem. The concepts behind the practical examples in this article apply beyond JavaScript, and are just the beginning when it comes to properly handling DateTime data and calculations. Plus, every helper library will come with its own set of nuances—which is even true of the eventual official standard support{target=”_blank”} for these types of operations.

The bottom line is: Use ISO on the back end, and leave the front end to format things properly for the user. Professional programmers will be aware of some of the nuances, and will (all the more decidedly) use well-supported DateTime libraries on both the back end and the front end. Built-in functions on the database side are another story, but hopefully this article gives enough background to make wiser decisions in that context, too.

Original article source at: https://www.toptal.com/

#datetime #javascript 

The Definitive Guide to DateTime Manipulation

A Flutter DateTime Picker Package

Omni DateTime Picker

A DateTime picker that lets user select a date and the time, with start & end as a range.

Screenshots

Omni DateTime Picker - Light

Omni DateTime Range Picker - Dark

Getting started

Add this to your package's pubspec.yaml file and run flutter pub get:

dependencies:
  omni_datetime_picker: ^0.1.2

Now in your Dart code, you can use:

import 'package:omni_datetime_picker/omni_datetime_picker.dart';

Usage

Simple usage:

OmniDateTimePicker

DateTime? dateTime = await showOmniDateTimePicker(context: context);

OmniDateTimeRangePicker

List<DateTime>? dateTimeList = await showOmniDateTimeRangePicker(context: context);

Custom properties:

OmniDateTimePicker

DateTime? dateTime = await showOmniDateTimePicker(
              context: context,
              type: OmniDateTimePickerType.dateAndTime,
              primaryColor: Colors.cyan,
              backgroundColor: Colors.grey[900],
              calendarTextColor: Colors.white,
              tabTextColor: Colors.white,
              unselectedTabBackgroundColor: Colors.grey[700],
              buttonTextColor: Colors.white,
              timeSpinnerTextStyle:
                  const TextStyle(color: Colors.white70, fontSize: 18),
              timeSpinnerHighlightedTextStyle:
                  const TextStyle(color: Colors.white, fontSize: 24),
              is24HourMode: false,
              isShowSeconds: false,
              startInitialDate: DateTime.now(),
              startFirstDate:
                  DateTime(1600).subtract(const Duration(days: 3652)),
              startLastDate: DateTime.now().add(
                const Duration(days: 3652),
              ),
              borderRadius: const Radius.circular(16),
            );

OmniDateTimeRangePicker

List<DateTime>? dateTimeList = await showOmniDateTimeRangePicker(
              context: context,
              type: OmniDateTimePickerType.dateAndTime,
              primaryColor: Colors.cyan,
              backgroundColor: Colors.grey[900],
              calendarTextColor: Colors.white,
              tabTextColor: Colors.white,
              unselectedTabBackgroundColor: Colors.grey[700],
              buttonTextColor: Colors.white,
              timeSpinnerTextStyle:
                  const TextStyle(color: Colors.white70, fontSize: 18),
              timeSpinnerHighlightedTextStyle:
                  const TextStyle(color: Colors.white, fontSize: 24),
              is24HourMode: false,
              isShowSeconds: false,
              startInitialDate: DateTime.now(),
              startFirstDate:
                  DateTime(1600).subtract(const Duration(days: 3652)),
              startLastDate: DateTime.now().add(
                const Duration(days: 3652),
              ),
              endInitialDate: DateTime.now(),
              endFirstDate: DateTime(1600).subtract(const Duration(days: 3652)),
              endLastDate: DateTime.now().add(
                const Duration(days: 3652),
              ),
              borderRadius: const Radius.circular(16),
            );

The returned value of showOmniDateTimeRangePicker() will be a List with two DateTime: [startDateTime, endDateTime].

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add omni_datetime_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  omni_datetime_picker: ^0.1.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:omni_datetime_picker/omni_datetime_picker.dart'; 

example/main.dart

import 'package:flutter/material.dart';
import 'package:omni_datetime_picker/omni_datetime_picker.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Omni DateTime Picker',
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () async {
                  DateTime? dateTime =
                      await showOmniDateTimePicker(context: context);
                },
                child: const Text("Show DateTime Picker"),
              ),
              ElevatedButton(
                onPressed: () async {
                  List<DateTime>? dateTimeList =
                      await showOmniDateTimeRangePicker(
                    context: context,
                    primaryColor: Colors.cyan,
                    backgroundColor: Colors.grey[900],
                    calendarTextColor: Colors.white,
                    tabTextColor: Colors.white,
                    unselectedTabBackgroundColor: Colors.grey[700],
                    buttonTextColor: Colors.white,
                    timeSpinnerTextStyle:
                        const TextStyle(color: Colors.white70, fontSize: 18),
                    timeSpinnerHighlightedTextStyle:
                        const TextStyle(color: Colors.white, fontSize: 24),
                    is24HourMode: false,
                    isShowSeconds: false,
                    startInitialDate: DateTime.now(),
                    startFirstDate:
                        DateTime(1600).subtract(const Duration(days: 3652)),
                    startLastDate: DateTime.now().add(
                      const Duration(days: 3652),
                    ),
                    endInitialDate: DateTime.now(),
                    endFirstDate:
                        DateTime(1600).subtract(const Duration(days: 3652)),
                    endLastDate: DateTime.now().add(
                      const Duration(days: 3652),
                    ),
                    borderRadius: const Radius.circular(16),
                  );
                },
                child: const Text("Show DateTime Range Picker"),
              ),
              ElevatedButton(
                onPressed: () async {
                  List<DateTime>? dateTimeList =
                      await showOmniDateTimeRangePicker(
                    context: context,
                    type: OmniDateTimePickerType.date,
                    primaryColor: Colors.cyan,
                    backgroundColor: Colors.grey[900],
                    calendarTextColor: Colors.white,
                    tabTextColor: Colors.white,
                    unselectedTabBackgroundColor: Colors.grey[700],
                    buttonTextColor: Colors.white,
                    timeSpinnerTextStyle:
                        const TextStyle(color: Colors.white70, fontSize: 18),
                    timeSpinnerHighlightedTextStyle:
                        const TextStyle(color: Colors.white, fontSize: 24),
                    is24HourMode: false,
                    isShowSeconds: false,
                    startInitialDate: DateTime.now(),
                    startFirstDate:
                        DateTime(1600).subtract(const Duration(days: 3652)),
                    startLastDate: DateTime.now().add(
                      const Duration(days: 3652),
                    ),
                    endInitialDate: DateTime.now(),
                    endFirstDate:
                        DateTime(1600).subtract(const Duration(days: 3652)),
                    endLastDate: DateTime.now().add(
                      const Duration(days: 3652),
                    ),
                    borderRadius: const Radius.circular(16),
                  );
                },
                child: const Text("Show DateTime Range Picker without Time"),
              ),
            ],
          ),
        ),
      ),
    );
  }
} 

Download Details:

Author: Type0N1

Source Code: https://github.com/Type0N1/OmniDateTimePicker

#picker #datetime #flutter 

A Flutter DateTime Picker Package
Nigel  Uys

Nigel Uys

1663232480

10 Best Golang Date and Time Library

In today's post we will learn about 10 Best Golang Date and Time Library.

Software is designed to make it easier to get work done, and for many people, that includes interacting with dates and times. Date and time values show up everywhere in modern software. For example, keeping track of when a car needs service and letting the owner know, keeping track of changes in a database to create an audit log, or just comparing one time to another to determine how long a process took. Therefore, retrieving the current time, manipulating time values to extract information from them, and displaying them to users in an easy-to-understand format are essential properties of an application.

In this tutorial, you will create a Go program to get the current local time of your computer, then print it to the screen in a format that is easier for people to read. Next, you will interpret a string to extract the date and time information. You will also translate the date and time values between two time zones, as well as add or subtract time values to determine the interval between two times.

Table of contents:

  • Carbon - A simple, semantic and developer-friendly golang package for datetime.
  • Carbon - Simple Time extension with a lot of util methods, ported from PHP Carbon library.
  • Cronrange - Parses Cron-style time range expressions, checks if the given time is within any ranges.
  • Date - Augments Time for working with dates, date ranges, time spans, periods, and time-of-day.
  • Dateparse - Parse date's without knowing format in advance.
  • Durafmt - Time duration formatting library for Go.
  • Feiertage - Set of functions to calculate public holidays in Germany, incl. specialization on the states of Germany (Bundesländer). Things like Easter, Pentecost, Thanksgiving...
  • Go-persian-calendar - The implementation of the Persian (Solar Hijri) Calendar in Go (golang).
  • Go-str2duration - Convert string to duration. Support time.Duration returned string and more.
  • Go-sunrise - Calculate the sunrise and sunset times for a given location.

1 - Carbon: A simple, semantic and developer-friendly golang package for datetime.

Introduction

A simple, semantic and developer-friendly golang package for datetime

Carbon has been included by awesome-go, if you think it is helpful, please give me a star

Installation

Go version >= 1.16 (recommend)

// By github
go get -u github.com/golang-module/carbon/v2

import (
	"github.com/golang-module/carbon/v2"
)

// By gitee
go get -u gitee.com/golang-module/carbon/v2

import (
	"gitee.com/golang-module/carbon/v2"
)

Go version < 1.16 (must)

// By github
go get -u github.com/golang-module/carbon

import (
	"github.com/golang-module/carbon"
)

// By gitee
go get -u gitee.com/golang-module/carbon

import (
	"gitee.com/golang-module/carbon"
)

Please refer to FAQ for the difference between v1 and v2

View on Github

2 - Carbon: Simple Time extension with a lot of util methods, ported from PHP Carbon library.

Features:

  • Time is embedded into Carbon (provides access to all of Time's functionality)
  • Supports addition and subtraction of dates
  • Provides methods to compare dates
  • Supports date formatting in common formats
  • Easily calculate difference between dates
  • Ease testing with dates by using carbon.Freeze() and carbon.Now()

To do:

  • Implement all localization features as in Carbon
  • Improve the code style to be more idiomatic Go

Getting started

Install Carbon:

go get github.com/uniplaces/carbon

Add to your imports to start using Carbon

import "github.com/uniplaces/carbon"

Examples

A simple example to get you started:

package main

import (
	"fmt"
	"time"

	"github.com/uniplaces/carbon"
)

func main() {
	fmt.Printf("Right now is %s\n", carbon.Now().DateTimeString())

	today, _ := carbon.NowInLocation("America/Vancouver")
	fmt.Printf("Right now in Vancouver is %s\n", today)

	fmt.Printf("Tomorrow is %s\n", carbon.Now().AddDay())
	fmt.Printf("Last week is %s\n", carbon.Now().SubWeek())

	nextOlympics, _ := carbon.CreateFromDate(2016, time.August, 5, "Europe/London")
	nextOlympics = nextOlympics.AddYears(4)
	fmt.Printf("Next olympics are in %d\n", nextOlympics.Year())

	if carbon.Now().IsWeekend() {
		fmt.Printf("Party time!")
	}
}

You can also check the examples/ folder for more examples.

View on Github

3 - Cronrange: Parses Cron-style time range expressions, checks if the given time is within any ranges.

cronrange is a Go package for time range expression in Cron style.

In a nutshell, CronRange expression is a combination of Cron expression and time duration to represent periodic time ranges, i.e. Cron for TimeRange. And it made easier to tell if the moment falls within the any time ranges (use IsWithin() method), and what's the next occurrence (use NextOccurrences() method).

For example, every New Year's Day in Tokyo can be written as:

DR=1440; TZ=Asia/Tokyo; 0 0 1 1 *

It consists of three parts separated by a semicolon:

  • DR=1440 stands for duration in minutes, 60 * 24 = 1440 min;
  • TZ=Asia/Tokyo is optional and for time zone using name in IANA Time Zone database;
  • 0 0 1 1 * is a cron expression representing the beginning of the time range.

Installation

To download the package:

go get -u github.com/1set/cronrange

Usage

To import it in your program as:

import "github.com/1set/cronrange"

Examples can be found in GoDoc.

View on Github

4 - Date: Augments Time for working with dates, date ranges, time spans, periods, and time-of-day.

Package date provides functionality for working with dates.

This package introduces a light-weight Date type that is storage-efficient and convenient for calendrical calculations and date parsing and formatting (including years outside the [0,9999] interval).

It also provides

  • clock.Clock which expresses a wall-clock style hours-minutes-seconds with millisecond precision.
  • period.Period which expresses a period corresponding to the ISO-8601 form (e.g. "PT30S").
  • timespan.DateRange which expresses a period between two dates.
  • timespan.TimeSpan which expresses a duration of time between two instants.
  • view.VDate which wraps Date for use in templates etc.

See package documentation for full documentation and examples.

Installation

go get -u github.com/rickb777/date

or

dep ensure -add github.com/rickb777/date

Status

This library has been in reliable production use for some time. Versioning follows the well-known semantic version pattern.

View on Github

5 - Dateparse: Parse date's without knowing format in advance.

Parse many date strings without knowing format in advance. Uses a scanner to read bytes and use a state machine to find format. Much faster than shotgun based parse methods. See bench_test.go for performance comparison.

MM/DD/YYYY VS DD/MM/YYYY Right now this uses mm/dd/yyyy WHEN ambiguous if this is not desired behavior, use ParseStrict which will fail on ambiguous date strings.

Timezones The location your server is configured affects the results! See example or https://play.golang.org/p/IDHRalIyXh and last paragraph here https://golang.org/pkg/time/#Parse.

// Normal parse.  Equivalent Timezone rules as time.Parse()
t, err := dateparse.ParseAny("3/1/2014")

// Parse Strict, error on ambigous mm/dd vs dd/mm dates
t, err := dateparse.ParseStrict("3/1/2014")
> returns error 

// Return a string that represents the layout to parse the given date-time.
layout, err := dateparse.ParseFormat("May 8, 2009 5:57:51 PM")
> "Jan 2, 2006 3:04:05 PM"

cli tool for testing dateformats

Date Parse CLI

View on Github

6 - Durafmt: Time duration formatting library for Go.

durafmt is a tiny Go library that formats time.Duration strings (and types) into a human readable format.

go get github.com/hako/durafmt

Why

If you've worked with time.Duration in Go, you most likely have come across this:

53m28.587093086s // :)

The above seems very easy to read, unless your duration looks like this:

354h22m3.24s // :S

Usage

durafmt.ParseString()

package main

import (
	"fmt"
	"github.com/hako/durafmt"
)

func main() {
	duration, err := durafmt.ParseString("354h22m3.24s")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
	// duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
}

View on Github

7 - Feiertage: Set of functions to calculate public holidays in Germany, incl. specialization on the states of Germany (Bundesländer). Things like Easter, Pentecost, Thanksgiving...

Feiertage is a Go/Golang library for calculating German and Austrian bank holidays. It includes the calculation of the date of Easter and, more importantly, offers ways to retrieve public holidays for a state of Germany or Austria (=Bundesland).

The library is probably useful only for people realizing use cases with special requirements inside of Austria or Germany, such as shift schedules or capacity calculation.

Usage:

There are two types of functions:

  • <feiertag>(year) and
  • <region>(year optional:IncludingSundays:true)

<feiertag> returns an extended time object (type feiertag). It carries the date of the holiday in the requested year plus the name of the holiday. <feiertag> may be any of the following:

   
NeujahrEpiphaniasHeiligeDreiKönige
ValentinstagInternationalerTagDesGedenkensAnDieOpferDesHolocaustJosefitag
WeiberfastnachtKarnevalssonntagRosenmontag
FastnachtAschermittwochInternationalerFrauentag
PalmsonntagGründonnerstagKarfreitag
OsternBeginnSommerzeitOstermontag
WalpurgisnachtTagDerArbeitTagDerBefreiung
StaatsfeiertagInternationalerTagDerPressefreiheitFlorianitag
MuttertagHandtuchtagChristiHimmelfahrt
VatertagPfingstenPfingstmontag
DreifaltigkeitssonntagFronleichnamTagDesMeeres
MariäHimmelfahrtSystemAdministratorAppreciationDayRupertitag
InternationalerKindertagWeltflüchtlingstagTagDerDeutschenEinheit
TagDerVolksabstimmungNationalfeiertagErntedankfest
ReformationstagHalloweenBeginnWinterzeit
AllerheiligenAllerseelenMartinstag
KarnevalsbeginnLeopolditagWeltkindertag
BußUndBettagThanksgivingBlackfriday
VolkstrauertagNikolausMariäUnbefleckteEmpfängnis
MariäEmpfängnisTotensonntagErsterAdvent
ZweiterAdventDritterAdventVierterAdvent
HeiligabendWeihnachtenChristtag
StefanitagZweiterWeihnachtsfeiertagSilvester

<region> returns an object of type region. It offers a list of public holidays valid in the specified state as well as the name and the shortname of the state as attributes. <region> may be any of:

   
BadenWürttembergBayernBerlin
BrandenburgBremenHamburg
HessenMecklenburgVorpommernNiedersachsen
NordrheinWestfalenRheinlandPfalzSaarland
SachsenSachsenAnhaltSchleswigHolstein
ThüringenDeutschlandBurgenland
KärntenNiederösterreichOberösterreich
SalzburgSteiermarkTirol
VorarlbergWienÖsterreich
All  

The optional region function argument includingSundays switches the behavior of the region function to include "gesetzliche Feiertage" that fall on Sundays in its output. This is important in Brandenburg, particularly for Easter and Pentecost Sunday. If you are calculating shift costs you will need to know even the holidays "hidden by Sunday".

The region functions return the public holidays ("gesetzliche Feiertage"). The function all returns all defined "special dates", such as Penance Day (Buß- und Bettag) or the begin/end of daylight saving time.

The regional functions for Austrian Bundesländer include saints' days which are state-level holidays, meaning schools etc. are generally closed but workers don't get the day off by default. If you don't want to include these days in your planning, it's okay to reference Österreich instead, as legal holidays are (more or less) synchronised across all Austrian states (Bundesländer).

View on Github

8 - Go-persian-calendar: The implementation of the Persian (Solar Hijri) Calendar in Go (golang).

Go Persian Calendar provides functionality for conversion among Persian (Solar Hijri) and Gregorian calendars. A Julian calendar is used as an interface for all conversions. The package name is ptime and it is compatible with the package time. All months are available with both Iranian and Dari Persian names. This source code is licensed under MIT license that can be found in the LICENSE file.

Installation

go get github.com/yaa110/go-persian-calendar

Getting started

1- Import the package ptime. Most of the time you need to import time and fmt packages, too.

import (
    ptime "github.com/yaa110/go-persian-calendar"
    "time"
    "fmt"
)

2- Convert Gregorian calendar to Persian calendar.

// Create a new instance of time.Time
var t time.Time = time.Date(2016, time.January, 1, 12, 1, 1, 0, ptime.Iran())

// Get a new instance of ptime.Time using time.Time
pt := ptime.New(t)

// Get the date in Persian calendar
fmt.Println(pt.Date()) // output: 1394 دی 11

3- Convert Persian calendar to Gregorian calendar.

// Create a new instance of ptime.Time
var pt ptime.Time = ptime.Date(1394, ptime.Mehr, 2, 12, 59, 59, 0, ptime.Iran())

// Get a new instance of time.Time
t := pt.Time()

// Get the date in Gregorian calendar
fmt.Println(t.Date()) // output: 2015 September 24

View on Github

9 - Go-str2duration: Convert string to duration. Support time.Duration returned string and more.

Go String To Duration (go-str2duration)

This package allows to get a time.Duration from a string. The string can be a string retorned for time.Duration or a similar string with weeks or days too!.

Download

go get github.com/xhit/go-str2duration/v2

Features

Go String To Duration supports this strings conversions to duration:

  • All strings returned in time.Duration String.
  • A string more readable like 1w2d6h3ns (1 week 2 days 6 hours and 3 nanoseconds).
  • µs and us are microsecond.

It's the same time.ParseDuration standard function in Go, but with days and week support.

Note: a day is 24 hour.

If you don't need days and weeks, use time.ParseDuration.

Usage

package main

import (
	"fmt"
	str2duration "github.com/xhit/go-str2duration/v2"
	"os"
	"time"
)

func main() {

    for i, tt := range []struct {
            dur      string
            expected time.Duration
        }{
            //This times are returned with time.Duration string
            {"1h", time.Duration(time.Hour)},
            {"1m", time.Duration(time.Minute)},
            {"1s", time.Duration(time.Second)},
            {"1ms", time.Duration(time.Millisecond)},
            {"1µs", time.Duration(time.Microsecond)},
            {"1us", time.Duration(time.Microsecond)},
            {"1ns", time.Duration(time.Nanosecond)},
            {"4.000000001s", time.Duration(4*time.Second + time.Nanosecond)},
            {"1h0m4.000000001s", time.Duration(time.Hour + 4*time.Second + time.Nanosecond)},
            {"1h1m0.01s", time.Duration(61*time.Minute + 10*time.Millisecond)},
            {"1h1m0.123456789s", time.Duration(61*time.Minute + 123456789*time.Nanosecond)},
            {"1.00002ms", time.Duration(time.Millisecond + 20*time.Nanosecond)},
            {"1.00000002s", time.Duration(time.Second + 20*time.Nanosecond)},
            {"693ns", time.Duration(693 * time.Nanosecond)},

            //This times aren't returned with time.Duration string, but are easily readable and can be parsed too!
            {"1ms1ns", time.Duration(time.Millisecond + 1*time.Nanosecond)},
            {"1s20ns", time.Duration(time.Second + 20*time.Nanosecond)},
            {"60h8ms", time.Duration(60*time.Hour + 8*time.Millisecond)},
            {"96h63s", time.Duration(96*time.Hour + 63*time.Second)},

            //And works with days and weeks!
            {"2d3s96ns", time.Duration(48*time.Hour + 3*time.Second + 96*time.Nanosecond)},
            {"1w2d3s96ns", time.Duration(168*time.Hour + 48*time.Hour + 3*time.Second + 96*time.Nanosecond)},

            {"10s1us693ns", time.Duration(10*time.Second + time.Microsecond + 693*time.Nanosecond)},

        } {
            durationFromString, err := str2duration.ParseDuration(tt.dur)
            if err != nil {
                panic(err)

            //Check if expected time is the time returned by the parser
            } else if tt.expected != durationFromString {
                 fmt.Println(fmt.Sprintf("index %d -> in: %s returned: %s\tnot equal to %s", i, tt.dur, durationFromString.String(), tt.expected.String()))
            }else{
                fmt.Println(fmt.Sprintf("index %d -> in: %s parsed succesfully", i, tt.dur))
            }
        }
}

View on Github

10 - Go-sunrise: Calculate the sunrise and sunset times for a given location.

Go package for calculating the sunrise and sunset times for a given location based on this method.

Usage

To calculate sunrise and sunset times, you will need the following information:

  • the date for which you wish to calculate the times
  • the latitude and longitudinal coordinates of the location

Begin by importing the package:

import "github.com/nathan-osman/go-sunrise"

Next, feed the information into the SunriseSunset() method:

rise, set := sunrise.SunriseSunset(
    43.65, -79.38,          // Toronto, CA
    2000, time.January, 1,  // 2000-01-01
)

The two return values will be the sunrise and sunset times for the location on the given day as time.Time values. If sun does not rise or set, both return values will be time.Time{}.

View on Github

Thank you for following this article.

Related videos:

Handling time in golang

#go #golang #datetime 

10 Best Golang Date and Time Library

Date and Time Selectors for Flutter

flutter_my_picker

适用于flutter的有关日期和时间的选择器,支持年份(showYearPicker)、月份(showMonthPicker)、日期(showDatePicker)、时间(showTimePicker)、日期时间(showDateTimePicker)等。

支持的平台

  • Android
  • IOS

image

使用方法

依赖安装

dependencies:
  ...
  flutter_my_picker: ^1.1.0

如果你想自己发布包,但是发布的时候报错,可以看这里发布教程

使用案例

导入 flutter_my_picker.dart;

import 'package:flutter_my_picker/flutter_my_picker.dart';

// 日期操作,需要时引入
import 'package:flutter_my_picker/common/date.dart';

年份选择器

_change(formatString) {
  return (_date) {
    setState(() {
      date = _date;
      dateStr = MyDate.format(formatString, _date);
    });
  };
}

MyPicker.showPicker(
  context: context,
  current: date,
  mode: MyPickerMode.year,
  onChange: _change('yyyy'),
);

// MyPicker.showYearPicker 效果一样,参数同上,不需要mode参数

月份选择器

MyPicker.showPicker(
  context: context,
  current: date,
  mode: MyPickerMode.month,
  onChange: _change('yyyy-MM'),
);

// MyPicker.showMonthPicker 效果一样,参数同上,不需要mode参数

日期选择器

MyPicker.showPicker(
  context: context,
  current: date,
  mode: MyPickerMode.date,
  onChange: _change('yyyy-MM-dd'),
);

// MyPicker.showDatePicker 效果一样,参数同上,不需要mode参数

时间选择器

MyPicker.showPicker(
  context: context,
  current: date,
  mode: MyPickerMode.time,
  onChange: _change('HH:mm'),
);

// MyPicker.showTimePicker 效果一样,参数同上,不需要mode参数

日期时间选择器

MyPicker.showPicker(
  context: context,
  current: date,
  mode: MyPickerMode.dateTime,
  onChange: _change('yyyy-MM-dd HH:mm'),
);

// MyPicker.showDateTimePicker 效果一样,参数同上,不需要mode参数

调用 MyPicker.showPicker 方法调起相关选择器,目前的参数有

API

MyPicker.showPicker所需要的的参数:

// 调用 showModalBottomSheet 所需
BuildContext context;

// 当前选中的时间,字符串和DateTime类型皆可,内部做了解析,mode 为 time 时, 可直接传入 '20:12' 的字符串
final dynamic current;
/// 开始时间,不传时表示不限制,mode 为 time 时, 可直接传入 '20:12' 的字符串
final dynamic start;
/// 结束时间,不传时表示不限制,mode 为 time 时, 可直接传入 '20:12' 的字符串
final dynamic end;

// 选中时间结束之后的回调,当滚动未结束时关闭弹窗就不会触发
//typedef DateChangedCallback(DateTime time)
final DateChangedCallback onChange;

// 点击确认按钮之后的回调
//typedef DateChangedCallback(DateTime time)
final DateChangedCallback onConfirm;

// 点击取消按钮之后的回调
//typedef CancelCallback()
final CancelCallback onCancel;

// 选择器模式
/**
enum MyPickerMode {
  year,
  month,
  date,
  time,
  dateTime,
}
*/
final MyPickerMode mode;

// 选择器单行的高度,默认36
final double itemHeight;

/// 挤压系数,默认 1, 建议设置 1.45
final double squeeze;

/// 被选中的内容放大系数,默认 1, 建议设置 1.2
final double magnification;

/// 被选中的内容偏移,默认 0, 建议设置 0.2
final double offAxisFraction; 

/// 是否显示头部,默认显示两边的按钮
final bool isShowHeader;

/// 头部的标题,需配合 isShowHeader 使用
final Widget title; 

/// 自定义头部,与 isShowHeader 和 title互斥
final Widget header; 

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_my_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_my_picker: ^1.1.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_my_picker/flutter_my_picker.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import './demo.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('使用案例'),
        ),
        body: DemoPage(),
      ),
    );
  }
} 

Download Details:

Author: ma125120

Source Code: https://github.com/ma125120/flutter_my_picker

#flutter #picker #datetime 

Date and Time Selectors for Flutter

CSV IO: Read, Write Delimited Text Files with Support Of Decimal Comma

ReadWriteDlm2

CSV IO Supports Decimal Comma, Date, DateTime, Time, Complex, Missing and Rational

ReadWriteDlm2 functions readdlm2(), writedlm2(), readcsv2() and writecsv2() are similar to those of stdlib.DelimitedFiles, but with additional support for Dates formats, Complex, Rational, Missing types and special decimal marks. ReadWriteDlm2 supports the Tables.jl interface.

For "decimal dot" users the functions readcsv2() and writecsv2() have the respective defaults: Delimiter is ',' (fixed) and decimal='.'.

The basic idea of readdlm2() and writedlm2() is to support the decimal comma countries. These functions use ';' as default delimiter and ',' as default decimal mark. "Decimal dot" users of these functions need to define decimal='.'.

Alternative package: CSV (supports also special decimal marks)

Installation

This package is registered and can be installed within the Pkg REPL-mode: Type ] in the REPL and then:

pkg> add ReadWriteDlm2

Basic Example(-> more): How To Use ReadWriteDlm2

julia> using ReadWriteDlm2, Dates           # activate modules ReadWriteDlm2, Dates

julia> a = ["text" 1.2; Date(2017,1,1) 1];  # create array with: String, Date, Float64 and Int eltype

julia> writedlm2("test.csv", a)             # test.csv(decimal comma): "text;1,2\n2017-01-01;1\n"

julia> readdlm2("test.csv")                 # read `CSV` data: All four eltypes are parsed correctly!
2×2 Array{Any,2}:
 "text"      1.2
 2017-01-01  1

julia> using DataFrames                     # Tables interface: auto Types for DataFrame columns

julia> DataFrame(readdlm2("test.csv", tables=true))
2×2 DataFrame
│ Row │ Column1    │ Column2 │
│     │ Any        │ Real    │
├─────┼────────────┼─────────┤
│ 1   │ text       │ 1.2     │
│ 2   │ 2017-01-01 │ 1       │

Function readdlm2()

Read a matrix from source. The source can be a text file, stream or byte array. Each line, separated by eol (default is '\n'), gives one row. The columns are separated by ';', another delim can be defined.

readdlm2(source; options...)
readdlm2(source, T::Type; options...)
readdlm2(source, delim::Char; options...)
readdlm2(source, delim::Char, T::Type; options...)
readdlm2(source, delim::Char, eol::Char; options...)
readdlm2(source, delim::Char, T::Type, eol::Char; options...)

Pre-processing of source with regex substitution changes the decimal marks from d,d to d.d. For default rs the keyword argument decimal=',' sets the decimal Char in the r-string of rs. When a special regex substitution tuple rs=(r.., s..) is defined, the argument decimal is not used ( -> Example). Pre-processing can be switched off with: rs=().

In addition to stdlib readdlm(), data is also parsed for Dates formats (ISO), theTime format HH:MM[:SS[.s{1,9}]] and for complex and rational numbers. To deactivate parsing dates/time set: dfs="", dtfs="". locale defines the language of day (E, e) and month (U, u) names.

The result will be a (heterogeneous) array of default element type Any. If header=true it will be a tuple containing the data array and a vector for the columnnames. Other (abstract) types for the data array elements could be defined. If data is empty, a 0×0 Array{T,2} is returned.

With tables=true[, header=true] option[s] a Tables interface compatible MatrixTable with individual column types is returned, which for example can be used as argument for DataFrame().

Additional Keyword Arguments readdlm2()

  • decimal=',': Decimal mark Char used by default rs, irrelevant if rs-tuple is not the default one
  • rs=(r"(\d),(\d)", s"\1.\2"): Regex (r,s)-tuple, the default change d,d to d.d if decimal=','
  • dtfs="yyyy-mm-ddTHH:MM:SS.s": Format string for DateTime parsing
  • dfs="yyyy-mm-dd": Format string for Date parsing
  • locale="english": Language for parsing dates names, default is english
  • tables=false: Return Tables interface compatible MatrixTable if true
  • dfheader=false: dfheader=true is shortform for tables=true, header=true
  • missingstring="na": How missing values are represented, default is "na"

Function readcsv2()

readcsv2(source, T::Type=Any; opts...)

Equivalent to readdlm2() with delimiter ',' and decimal='.'.

Documentation For Base readdlm()

More information about Base functionality and (keyword) arguments - which are also supported by readdlm2() and readcsv2() - is available in the documentation for readdlm().

Compare Default Functionality readdlm() - readdlm2() - readcsv2()

ModuleFunctionDelimiterDec. MarkElement TypeExt. Parsing
DelimitedFilesreaddlm()' ''.'Float64/AnyNo (String)
ReadWriteDlm2readdlm2()';'','AnyYes
ReadWriteDlm2readcsv2()',''.'AnyYes
ReadWriteDlm2readdlm2(opt:tables=true)';'','Column spec.Yes, + col T
ReadWriteDlm2readcsv2(opt:tables=true)',''.'Column spec.Yes, + col T

Function writedlm2()

Write A (a vector, matrix, or an iterable collection of iterable rows, a Tables source) as text to f (either a filename or an IO stream). The columns are separated by ';', another delim (Char or String) can be defined.

writedlm2(f, A; options...)
writedlm2(f, A, delim; options...)

By default, a pre-processing of values takes place. Before writing as strings, decimal marks are changed from '.' to ','. With a keyword argument another decimal mark can be defined. To switch off this pre-processing set: decimal='.'.

In writedlm2() the output format for Date and DateTime data can be defined with format strings. Defaults are the ISO formats. Day (E, e) and month (U, u) names are written in the locale language. For writing Complex numbers the imaginary component suffix can be selected with the imsuffix= keyword argument.

Additional Keyword Arguments writedlm2()

  • decimal=',': Character for writing decimal marks, default is a comma
  • dtfs="yyyy-mm-ddTHH:MM:SS.s": Format string, DateTime write format
  • dfs="yyyy-mm-dd": Format string, Date write format
  • locale="english": Language for writing date names, default is english
  • imsuffix="im": Complex - imaginary component suffix "im"(=default), "i" or "j"
  • missingstring="na": How missing values are written, default is "na"

Function writecsv2()

writecsv2(f, A; opts...)

Equivalent to writedlm2() with fixed delimiter ',' and decimal='.'.

Compare Default Functionality writedlm() - writedlm2() - writecsv2()

ModuleFunctionDelimiterDecimal Mark
DelimitedFileswritedlm()'\t''.'
ReadWriteDlm2writedlm2()';'','
ReadWriteDlm2writecsv2()',''.'

More Examples

writecsv2() And readcsv2()

julia> using ReadWriteDlm2

julia> a = Any[1 complex(1.5,2.7);1.0 1//3];   # create array with: Int, Complex, Float64 and Rational type

julia> writecsv2("test.csv", a)                # test.csv(decimal dot): "1,1.5+2.7im\n1.0,1//3\n"

julia> readcsv2("test.csv")                    # read CSV data: All four types are parsed correctly!
2×2 Array{Any,2}:
 1    1.5+2.7im
 1.0    1//3

writedlm2() And readdlm2() With Special decimal=

julia> using ReadWriteDlm2

julia> a = Float64[1.1 1.2;2.1 2.2]
2×2 Array{Float64,2}:
 1.1  1.2
 2.1  2.2

julia> writedlm2("test.csv", a; decimal='€')     # '€' is decimal Char in 'test.csv'

julia> readdlm2("test.csv", Float64; decimal='€')      # a) standard: use keyword argument
2×2 Array{Float64,2}:
 1.1  1.2
 2.1  2.2

julia> readdlm2("test.csv", Float64; rs=(r"(\d)€(\d)", s"\1.\2"))    # b) more flexible: rs-Regex-Tupel
2×2 Array{Float64,2}:
 1.1  1.2
 2.1  2.2

writedlm2() And readdlm2() With Union{Missing, Float64}

julia> using ReadWriteDlm2

julia> a = Union{Missing, Float64}[1.1 0/0;missing 2.2;1/0 -1/0]
3×2 Array{Union{Missing, Float64},2}:
   1.1        NaN
    missing     2.2
 Inf         -Inf

julia> writedlm2("test.csv", a; missingstring="???")     # use "???" for missing data

julia> read("test.csv", String)
"1,1;NaN\n???;2,2\nInf;-Inf\n"

julia> readdlm2("test.csv", Union{Missing, Float64}; missingstring="???")
3×2 Array{Union{Missing, Float64},2}:
   1.1        NaN
    missing     2.2
 Inf         -Inf

Date And DateTime With locale="french"

julia> using ReadWriteDlm2, Dates

julia> Dates.LOCALES["french"] = Dates.DateLocale(
           ["janvier", "février", "mars", "avril", "mai", "juin",
               "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
           ["janv", "févr", "mars", "avril", "mai", "juin",
               "juil", "août", "sept", "oct", "nov", "déc"],
           ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"],
           ["lu", "ma", "me", "je", "ve", "sa", "di"],
           );

julia> a = hcat([Date(2017,1,1), DateTime(2017,1,1,5,59,1,898), 1, 1.0, "text"])
5x1 Array{Any,2}:
  2017-01-01
  2017-01-01T05:59:01.898
 1
 1.0
  "text"

julia> writedlm2("test.csv", a; dfs="E, d.U yyyy", dtfs="e, d.u yyyy H:M:S,s", locale="french")

julia> read("test.csv", String)  # to see what have been written in "test.csv" file
"dimanche, 1.janvier 2017\ndi, 1.janv 2017 5:59:1,898\n1\n1,0\ntext\n"

julia> readdlm2("test.csv"; dfs="E, d.U yyyy", dtfs="e, d.u yyyy H:M:S,s", locale="french")
5×1 Array{Any,2}:
  2017-01-01
  2017-01-01T05:59:01.898
 1
 1.0
  "text"

Tables-Interface Examples With DataFrames

See -> DataFrames for installation and more information.

julia> using ReadWriteDlm2, Dates, DataFrames, Statistics

Write CSV: Using Tables interface and create from DataFrame

julia> df = DataFrame(                                # Create DataFrame `df`
    date = [Date(2017,1,1), Date(2017,1,2), nothing],
    value_1 = [1.4, 1.8, missing],
    value_2 = [2, 3, 4]
    )
3×3 DataFrame
│ Row │ date       │ value_1  │ value_2 │
│     │ Union…     │ Float64⍰ │ Int64   │
├─────┼────────────┼──────────┼─────────┤
│ 1   │ 2017-01-01 │ 1.4      │ 2       │
│ 2   │ 2017-01-02 │ 1.8      │ 3       │
│ 3   │            │ missing  │ 4       │

julia> writedlm2("testdf_com.csv", df)   # decimal comma: write DataFrame df

julia> read("testdf_com.csv", String)    # check csv data
"date;value_1;value_2\n2017-01-01;1,4;2\n2017-01-02;1,8;3\nnothing;na;4\n"

Read CSV: Using Tables interface and create a DataFrame

julia> df2 = DataFrame(readdlm2("testdf_com.csv", header=true, tables=true))
3×3 DataFrame
│ Row │ date       │ value_1  │ value_2 │
│     │ Union…     │ Float64⍰ │ Int64   │
├─────┼────────────┼──────────┼─────────┤
│ 1   │ 2017-01-01 │ 1.4      │ 2       │
│ 2   │ 2017-01-02 │ 1.8      │ 3       │
│ 3   │            │ missing  │ 4       │

julia> mean(skipmissing(df2[!, :value_1]))
1.6

julia> mean(df2[!, :value_2])
3.0

Download Details:

Author: Strickek
Source Code: https://github.com/strickek/ReadWriteDlm2.jl 
License: MIT license

#julia #text #datetime 

CSV IO: Read, Write Delimited Text Files with Support Of Decimal Comma

Flutter Date Time Helper

Finap Datetime Helper

Features

Utility functions for Date Time

Getting started

Run this command to install

flutter pub add finap_datetime_helper

Usage

Get now as Miliseconds

static int getNowFromMilliseconds() {
    try {
      return DateTime.now().toUtc().millisecondsSinceEpoch;
    } on Exception catch (e) {
      print(e.toString());
      return 0;
    }
  }

get Date time from miliseconds

static DateTime? getDate(int miliseconds) {
    try {
      return DateTime.fromMillisecondsSinceEpoch(miliseconds, isUtc: true);
    } on Exception catch (e) {
      print(e.toString());
      return null;
    }
  }

get string date from miliseconds

static String? getDateString(int? miliseconds) {
    final formatter = DateFormat('dd-MMM-yyyy hh:mm a');
    if (miliseconds == null) return '';
    final date = getDate(miliseconds);
    if (date != null) {
      return formatter.format(date.toLocal());
    }
    return '';
  }

get Date in seconds

static String? getDateInSecondsString(int? seconds) {
    final formatter = DateFormat('dd-MMM-yyyy hh:mm a');
    if (seconds == null) return '';
    final date = getDate(seconds * 1000);
    if (date != null) {
      return formatter.format(date.toLocal());
    }
    return '';
  }

get Only date string by providing miliseconds

static String? getOnlyDateString(int? miliseconds) {
    final formatter = DateFormat('dd-MMM-yyyy');
    if (miliseconds == null) return '';
    final date = getDate(miliseconds);
    if (date != null) {
      return formatter.format(date.toLocal());
    }
    return '';
  }

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add finap_datetime_helper

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  finap_datetime_helper: ^0.0.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:finap_datetime_helper/finap_datetime_helper.dart'; 

Download Details:

Author: 

Source Code: https://pub.dev/packages/finap_datetime_helper

#flutter #datetime 

Flutter Date Time Helper

A Date Time Picker for Flutter

Notice

This was forked from https://github.com/Realank/flutter_datetime_picker since the author is inactive.

Will accept PRs and try to solve issues.

Flutter Datetime Picker

(Pub) flutter_datetime_picker_bdaya

A flutter date time picker inspired by flutter-cupertino-date-picker

you can choose date / time / date&time in multiple languages:

  • Albanian(sq)
  • Arabic(ar)
  • Armenian(hy)
  • Azerbaijan(az)
  • Basque(eu)
  • Bengali(bn)
  • Bulgarian(bg)
  • Catalan(cat)
  • Chinese(zh)
  • Danish(da)
  • Dutch(nl)
  • English(en)
  • French(fr)
  • German(de)
  • Hebrew(he)
  • Indonesian(id)
  • Italian(it)
  • Japanese(jp)
  • Kazakh(kk)
  • Korean(ko)
  • Persian(fa)
  • Polish (pl)
  • Portuguese(pt)
  • Russian(ru)
  • Spanish(es)
  • Swedish(sv)
  • Thai(th)
  • Turkish(tr)
  • Vietnamese(vi)
  • Khmer(kh)

and you can also custom your own picker content

Date pickerTime pickerDate Time picker

International:

Date Time picker (Chinese)Date Time picker (America)Date Time picker (Dutch)Date Time picker (Russian)

Demo App

main page

Usage

TextButton(
    onPressed: () {
        DatePicker.showDatePicker(context,
                              showTitleActions: true,
                              minTime: DateTime(2018, 3, 5),
                              maxTime: DateTime(2019, 6, 7), onChanged: (date) {
                            print('change $date');
                          }, onConfirm: (date) {
                            print('confirm $date');
                          }, currentTime: DateTime.now(), locale: LocaleType.zh);
    },
    child: Text(
        'show date time picker (Chinese)',
        style: TextStyle(color: Colors.blue),
    ));

Customize

If you want to customize your own style of date time picker, there is a class called CommonPickerModel, every type of date time picker is extended from this class, you can refer to other picker model (eg. DatePickerModel), and write your custom one, then pass this model to showPicker method, so that your own date time picker will appear, it’s easy, and will perfectly meet your demand

How to customize your own picker model:

class CustomPicker extends CommonPickerModel {
  String digits(int value, int length) {
    return '$value'.padLeft(length, "0");
  }

  CustomPicker({DateTime currentTime, LocaleType locale}) : super(locale: locale) {
    this.currentTime = currentTime ?? DateTime.now();
    this.setLeftIndex(this.currentTime.hour);
    this.setMiddleIndex(this.currentTime.minute);
    this.setRightIndex(this.currentTime.second);
  }

  @override
  String leftStringAtIndex(int index) {
    if (index >= 0 && index < 24) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String middleStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String rightStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String leftDivider() {
    return "|";
  }

  @override
  String rightDivider() {
    return "|";
  }

  @override
  List<int> layoutProportions() {
    return [1, 2, 1];
  }

  @override
  DateTime finalTime() {
    return currentTime.isUtc
        ? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
            this.currentLeftIndex(), this.currentMiddleIndex(), this.currentRightIndex())
        : DateTime(currentTime.year, currentTime.month, currentTime.day, this.currentLeftIndex(),
            this.currentMiddleIndex(), this.currentRightIndex());
  }
}

Getting Started

For help getting started with Flutter, view our online documentation.

For help on editing package code, view the documentation.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_datetime_picker_bdaya

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_datetime_picker_bdaya: ^2.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_datetime_picker_bdaya/flutter_datetime_picker_bdaya.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_bdaya/flutter_datetime_picker_bdaya.dart';

void main() => runApp(new MyApp());

class CustomPicker extends CommonPickerModel {
  String digits(int value, int length) {
    return '$value'.padLeft(length, "0");
  }

  CustomPicker({DateTime? currentTime, LocaleType? locale})
      : super(locale: locale) {
    this.currentTime = currentTime ?? DateTime.now();
    this.setLeftIndex(this.currentTime.hour);
    this.setMiddleIndex(this.currentTime.minute);
    this.setRightIndex(this.currentTime.second);
  }

  @override
  String? leftStringAtIndex(int index) {
    if (index >= 0 && index < 24) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String? middleStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String? rightStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }

  @override
  String leftDivider() {
    return "|";
  }

  @override
  String rightDivider() {
    return "|";
  }

  @override
  List<int> layoutProportions() {
    return [1, 2, 1];
  }

  @override
  DateTime finalTime() {
    return currentTime.isUtc
        ? DateTime.utc(
            currentTime.year,
            currentTime.month,
            currentTime.day,
            this.currentLeftIndex(),
            this.currentMiddleIndex(),
            this.currentRightIndex())
        : DateTime(
            currentTime.year,
            currentTime.month,
            currentTime.day,
            this.currentLeftIndex(),
            this.currentMiddleIndex(),
            this.currentRightIndex());
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Datetime Picker'),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            TextButton(
                onPressed: () {
                  DatePicker.showDatePicker(context,
                      showTitleActions: true,
                      minTime: DateTime(2018, 3, 5),
                      maxTime: DateTime(2019, 6, 7),
                      theme: DatePickerTheme(
                          headerColor: Colors.orange,
                          backgroundColor: Colors.blue,
                          itemStyle: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                          doneStyle:
                              TextStyle(color: Colors.white, fontSize: 16)),
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  }, currentTime: DateTime.now(), locale: LocaleType.en);
                },
                child: Text(
                  'show date picker(custom theme &date time range)',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showTimePicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  }, currentTime: DateTime.now());
                },
                child: Text(
                  'show time picker',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showTime12hPicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  }, currentTime: DateTime.now());
                },
                child: Text(
                  'show 12H time picker with AM/PM',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showDateTimePicker(context,
                      showTitleActions: true,
                      minTime: DateTime(2020, 5, 5, 20, 50),
                      maxTime: DateTime(2020, 6, 7, 05, 09), onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  }, locale: LocaleType.zh);
                },
                child: Text(
                  'show date time picker (Chinese)',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showDateTimePicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  }, currentTime: DateTime(2008, 12, 31, 23, 12, 34));
                },
                child: Text(
                  'show date time picker (English-America)',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showDateTimePicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  },
                      currentTime: DateTime(2008, 12, 31, 23, 12, 34),
                      locale: LocaleType.nl);
                },
                child: Text(
                  'show date time picker (Dutch)',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showDateTimePicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  },
                      currentTime: DateTime(2008, 12, 31, 23, 12, 34),
                      locale: LocaleType.ru);
                },
                child: Text(
                  'show date time picker (Russian)',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showDateTimePicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  },
                      currentTime: DateTime.utc(2019, 12, 31, 23, 12, 34),
                      locale: LocaleType.de);
                },
                child: Text(
                  'show date time picker in UTC (German)',
                  style: TextStyle(color: Colors.blue),
                )),
            TextButton(
                onPressed: () {
                  DatePicker.showPicker(context, showTitleActions: true,
                      onChanged: (date) {
                    print('change $date in time zone ' +
                        date.timeZoneOffset.inHours.toString());
                  }, onConfirm: (date) {
                    print('confirm $date');
                  },
                      pickerModel: CustomPicker(currentTime: DateTime.now()),
                      locale: LocaleType.en);
                },
                child: Text(
                  'show custom time picker,\nyou can custom picker model like this',
                  style: TextStyle(color: Colors.blue),
                )),
          ],
        ),
      ),
    );
  }
} 

Download Details:

Author: Bdaya-Dev

Source Code: https://github.com/Bdaya-Dev/flutter_datetime_picker

#flutter #datetime #picker 

A Date Time Picker for Flutter
Nat  Grady

Nat Grady

1659604680

Lubridate: Make Working with Dates in R Just That Little Bit Easier

lubridate

Overview

Date-time data can be frustrating to work with in R. R commands for date-times are generally unintuitive and change depending on the type of date-time object being used. Moreover, the methods we use with date-times must be robust to time zones, leap days, daylight savings times, and other time related quirks, and R lacks these capabilities in some situations. Lubridate makes it easier to do the things R does with date-times and possible to do the things R does not.

If you are new to lubridate, the best place to start is the date and times chapter in R for data science.

Installation

# The easiest way to get lubridate is to install the whole tidyverse:
install.packages("tidyverse")

# Alternatively, install just lubridate:
install.packages("lubridate")

# Or the the development version from GitHub:
# install.packages("devtools")
devtools::install_github("tidyverse/lubridate")

Cheatsheet

Features

library(lubridate, warn.conflicts = FALSE)

Easy and fast parsing of date-times: ymd(), ymd_hms, dmy(), dmy_hms, mdy(), …

ymd(20101215)
#> [1] "2010-12-15"
mdy("4/1/17")
#> [1] "2017-04-01"

Simple functions to get and set components of a date-time, such as year(), month(), mday(), hour(), minute() and second():

bday <- dmy("14/10/1979")
month(bday)
#> [1] 10
wday(bday, label = TRUE)
#> [1] Sun
#> Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat

year(bday) <- 2016
wday(bday, label = TRUE)
#> [1] Fri
#> Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat

Helper functions for handling time zones: with_tz(), force_tz()

time <- ymd_hms("2010-12-13 15:30:30")
time
#> [1] "2010-12-13 15:30:30 UTC"

# Changes printing
with_tz(time, "America/Chicago")
#> [1] "2010-12-13 09:30:30 CST"

# Changes time
force_tz(time, "America/Chicago")
#> [1] "2010-12-13 15:30:30 CST"

Lubridate also expands the type of mathematical operations that can be performed with date-time objects. It introduces three new time span classes borrowed from https://www.joda.org.

durations, which measure the exact amount of time between two points

periods, which accurately track clock times despite leap years, leap seconds, and day light savings time

intervals, a protean summary of the time information between two points

Code of Conduct

Please note that the lubridate project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Author: Tidyverse
Source Code: https://github.com/tidyverse/lubridate 
License: GPL-3.0 license

#r #datetime 

Lubridate: Make Working with Dates in R Just That Little Bit Easier
Lawson  Wehner

Lawson Wehner

1658806080

Simple_date: A Simple Date Model for Dart

Simple Date

A simple date class with no notion of time.

Can be used as a simpler alternative to Dart's DateTime.

Usage

final today = SimpleDate.today();
final moonLanding = SimpleDate(1969, 07, 20);

print(today.isAfter(moonLanding)); // true

final birthday = SimpleDate(1998, 07, 20);
final age = birthday.difference(today);
print(age); // My current age!

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add simple_date

With Flutter:

 $ flutter pub add simple_date

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  simple_date: ^1.0.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:simple_date/simple_date.dart';

example/simple_date_example.dart

// ignore_for_file: avoid_print
import 'package:simple_date/simple_date.dart';

void main() {
  final today = SimpleDate.today();
  final moonLanding = SimpleDate(1969, 07, 20);

  print(today.isAfter(moonLanding)); // true

  final birthday = SimpleDate(1998, 07, 20);
  final age = birthday.difference(today);
  print(age); // My current age!
}

Features and bugs

Please file feature requests and bugs at the GitHub repository.

Author: jeroen-meijer
Source Code: https://github.com/jeroen-meijer/simple_date 
License: MIT license

#flutter #dart #datetime 

Simple_date: A Simple Date Model for Dart
Mike  Kozey

Mike Kozey

1658474040

Date_time: Package to Work with Date & Time in Separation

 date_time

Package to work with Date & Time in separation and with its ranges.

This project will be useful for projects that are related to booking.

Features

  • Only Date comparison
  • Only Time comparison
  • Overflowed Time with keeping days
  • Find crossing of dates
  • Find crossing of times in the day

Getting started

  1. Add dependency
dependencies:
  date_time: <newest>
  1. Import the dependency
import 'package:date_time/date_time.dart';

Usage

Please, check (examples) folder for more advanced examples.

Date

// Get [Date] & [Time] from [DateTime]
print(DateTime(2022, 1, 6).date); // prints 1/6/2022
print(DateTime(7, 38, 24).time); // 07:38:24
given('DateTime', () {
  final dateTime = DateTime(2020, 11, 30, 14, 33, 17);

  then('[Date] should be equal to', () {
    dateTime.date.should.be(Date(year: 2020, month: 11, day: 30));
  });

  then('[Time] should be equal to', () {
    dateTime.time.should.be(Time(hour: 14, minute: 33, second: 17));
  });
});

CopyWith

final date = Date(year: 2021, month: 3, day: 7);
print(date.copyWith(year: 2022)); // prints 07/03/2022

DateRange

final range = DateRange(
  const Date(year: 2021, month: 1, day: 1),
  const Date(year: 2021, month: 12, day: 31),
);

test('should be valid', () {
  range.isValid.should.beTrue();
});

Time

final time2 = time.addMinutes(30);
final isTime2After = time2 > time;
final isTime2After2 = time2.isAfter(time);
print('Is time2 after: $isTime2After');

CopyWith

  final time = Time(hour: 6, minute: 30, second: 7);
  print(time);                      // prints 06:30:07
  print(time.copyWith(second: 0));  // prints 06:30:00

Overflowed Time

to keep days

final time = Time(hour: 20).addHours(5);

print(time is OverflowedTime); // prints `true`
print(time.asOverflowed.days); // prints `1`

TimeRange

// TimeRange crossing
final timeRange = TimeRange(Time.now, Time.now.addHours(6));
final timeRange2 = TimeRange(Time.now.addHours(3), Time.now.addHours(9));

final isCrossing = timeRange.isCross(timeRange2);
print('Time ranges are crossing: $isCrossing');

Override time with clock package

withClock(
    Clock(() => DateTime.now().subtract(Duration(days: 10, minutes: 214))),
    () {
        print(clock.now());                    // 2022-06-21 16:28:46.366887
        print(DateTime.now());                 // 2022-07-01 20:02:46.367579    
        print('${Date.now()} ${Time.now()}');  // 6/21/2022 16:28:46                  
    },
);

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add date_time

With Flutter:

 $ flutter pub add date_time

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  date_time: ^0.6.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:date_time/date_time.dart';

example/README.md

Examples

import 'package:date_time/date_time.dart';

void main() {
  final dateTime = DateTime.now();
  final date = dateTime.date;
  final time = dateTime.time;

  print('Date is $date');
  print('Time is $time');

  // Compare dates

  final date2 = date.addDays(1);
  final isDate2After = date2 >= date;
  final isDate2After2 = date2.isAfter(date);
  print('Is date2 after: $isDate2After');

  // Compare times
  final time2 = time.addMinutes(30);
  final isTime2After = time2 > time;
  final isTime2After2 = time2.isAfter(time);
  print('Is time2 after: $isTime2After');
}

Changelog

Please see the Changelog page to know what's recently changed.

Contributing

Feel free to contribute to this project.

If you find a bug or want a feature, but don't know how to fix/implement it, please fill an issue.
If you fixed a bug or implemented a new feature, please send a pull request.

We accept the following contributions:

  • New features
  • Improving documentation
  • Fixing bugs

Author: AndrewPiterov
Source Code: https://github.com/AndrewPiterov/date_time 
License: MIT license

#flutter #dart #datetime 

Date_time: Package to Work with Date & Time in Separation

A Dart Library That Expand DateTime

TODO: Put a short description of the package here that helps potential users know whether this package might be useful for them.

Features

  • get the sexagenary cycle(60-year cycle) in chinese date(干支).
  • get the era name of japanese in japanese date(日本年号).
  • get some information about month. like:
    • first day, last day
    • for each day (normal, reverse, async)
    • count of days

Getting started

  • import it like import 'package:big_date/big_date.dart';

Usage

first you must imort this package to use it.

import 'package:big_date/big_date.dart';

and then you can use it like this

Additional information

TODO: Tell users more about the package: where to find more information, how to contribute to the package, how to file issues, what response they can expect from the package authors, and more.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add big_date

With Flutter:

 $ flutter pub add big_date

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  big_date: ^0.2.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:big_date/big_date.dart'; 

example/big_date_example.dart

import 'package:big_date/big_date.dart';

void main() {
  final now = DateTime.now();
  print(now.lastMonth.lastMonth.lastMonth.dayCountOfMonth);
  DateTime.now().forEachDayOfMonthReverse((d) => print(d));
  print(now.format("%w"));
  print(now.toJapanDate().format("%W"));
  print(now.format("%_w"));
  print(now.toJapanDate().format("%_W"));
} 

Download Details:

Author: normidar

Source Code: https://github.com/normidar/big_date

#datetime #dart #ios #android 

A Dart Library That Expand DateTime
Reid  Rohan

Reid Rohan

1653989340

Jest-date-mock: Mock `Date` When Run Unit Test Cases with Jest

jest-date-mock

Mock Date when run unit test cases with jest. Make tests of Date easier.

Install

This should only be installed as a development dependency (devDependencies) as it is only designed for testing.

npm i --save-dev jest-date-mock

Setup

In your package.json under the jest, create a setupFiles array and add jest-date-mock to the array.

{
  "jest": {
    "setupFiles": ["jest-date-mock"]
  }
}

If you already have a setupFiles attribute you can also append jest-date-mock to the array.

{
  "jest": {
    "setupFiles": ["./__setups__/other.js", "jest-date-mock"]
  }
}

More about in configuration section.

Setup file

Alternatively you can create a new setup file which then requires this module or add the require statement to an existing setup file.

__setups__/date.js

import 'jest-date-mock';
// or
require('jest-date-mock');

Add that file to your setupFiles array:

"jest": {
  "setupFiles": [
    "./__setups__/date.js"
  ]
}

Usage

Use the only 3 api for test cases.

  • advanceBy(ms): advance date timestamp by ms.
  • advanceTo([timestamp]): reset date to timestamp, default to 0.
  • clear(): shut down the mock system.
import { advanceBy, advanceTo, clear } from 'jest-date-mock';

test('usage', () => {
  advanceTo(new Date(2018, 5, 27, 0, 0, 0)); // reset to date time.

  const now = Date.now();

  advanceBy(3000); // advance time 3 seconds
  expect(+new Date() - now).toBe(3000);

  advanceBy(-1000); // advance time -1 second
  expect(+new Date() - now).toBe(2000);

  clear();
  Date.now(); // will got current timestamp
});

More sample code here.

Also, add an API Date.current() to get the actual current timestamp.

import { advanceBy, advanceTo, clear } from 'jest-date-mock';

advanceTo(0); // reset to timestamp = 0

Date.now(); // will got 0

Date.current(); // will got the actual timestamp.

Author: Hustcc
Source Code: https://github.com/hustcc/jest-date-mock 
License: MIT license

#javascript #jest #datetime #mock 

Jest-date-mock: Mock `Date` When Run Unit Test Cases with Jest
Oral  Brekke

Oral Brekke

1653414780

Tinydate: A Tiny (349B) Reusable Date formatter. Extremely Fast!

tinydate

A tiny (349B) reusable date formatter. Extremely fast!

Inspired by tinytime, this module returns a "render" function that efficiently re-render your deconstructed template. This allows for incredibly performant results!

However, please notice that this only provides a limited subset of Date methods.
If you need more, tinytime or date-fns are great alternatives!

Install

$ npm install --save tinydate

Usage

const tinydate = require('tinydate');
const fooDate = new Date('5/1/2017, 4:30:09 PM');

const stamp = tinydate('Current time: [{HH}:{mm}:{ss}]');

stamp(fooDate);
//=> Current time: [16:30:09]

stamp();
//=> Current time: [17:09:34]

API

tinydate(pattern, dict?)(date?)

Returns: Function

Returns a rendering function that will optionally accept a date value as its only argument.

pattern

Type: String
Required: true

The template pattern to be parsed.

dict

Type: Object
Required: false

A custom dictionary of template patterns. You may override existing patterns or declare new ones.

Important: All dictionary items must be a function and must control its own formatting.
For example, when defining your own {ss} template, tinydate will not pad its value to two digits.

const today = new Date('2019-07-04, 5:30:00 PM');

// Example custom dictionary:
//   - Adds {MMMM}
//   - Overrides {DD}
const stamp = tinydate('Today is: {MMMM} {DD}, {YYYY}', {
	MMMM: d => d.toLocaleString('default', { month: 'long' }),
	DD: d => d.getDate()
});

stamp(today);
//=> 'Today is: July 4, 2019'

date

Type: Date
Default: new Date()

The date from which to retrieve values. Defaults to current datetime if no value is provided.

Patterns

  • {YYYY}: full year; eg: 2017
  • {YY}: short year; eg: 17
  • {MM}: month; eg: 04
  • {DD}: day; eg: 01
  • {HH}: hours; eg: 06 (24h)
  • {mm}: minutes; eg: 59
  • {ss}: seconds; eg: 09
  • {fff}: milliseconds; eg: 555

Benchmarks

# Node v10.13.0

tinydate    x 160,834,214 ops/sec ±0.21% (96 runs sampled)
tinytime    x  44,602,162 ops/sec ±0.34% (97 runs sampled)
time-stamp  x     888,153 ops/sec ±1.27% (86 runs sampled)

Demo

Author: lukeed
Source Code: https://github.com/lukeed/tinydate 
License: MIT license

#node #javascript #datetime 

Tinydate: A Tiny (349B) Reusable Date formatter. Extremely Fast!
Oral  Brekke

Oral Brekke

1653407280

Dayjs: Fast 2kB Alternative to Moment.js with The Same Modern API

Fast 2kB alternative to Moment.js with the same modern API 

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.

dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss');
  • 🕒 Familiar Moment.js API & patterns
  • 💪 Immutable
  • 🔥 Chainable
  • 🌐 I18n support
  • 📦 2kb mini library
  • 👫 All browsers supported

Getting Started

Documentation

You can find for more details, API, and other docs on day.js.org website.

Installation

npm install dayjs --save

📚Installation Guide

API

It's easy to use Day.js APIs to parse, validate, manipulate, and display dates and times.

dayjs('2018-08-08') // parse

dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // display

dayjs().set('month', 3).month() // get & set

dayjs().add(1, 'year') // manipulate

dayjs().isBefore(dayjs()) // query

📚API Reference

I18n

Day.js has great support for internationalization.

But none of them will be included in your build unless you use it.

import 'dayjs/locale/es' // load on demand

dayjs.locale('es') // use Spanish locale globally

dayjs('2018-05-05').locale('zh-cn').format() // use Chinese Simplified locale in a specific instance

📚Internationalization

Plugin

A plugin is an independent module that can be added to Day.js to extend functionality or add new features.

import advancedFormat from 'dayjs/plugin/advancedFormat' // load on demand

dayjs.extend(advancedFormat) // use plugin

dayjs().format('Q Do k kk X x') // more available formats

📚Plugin List

English | 简体中文 | 日本語 | Português Brasileiro | 한국어 | Español (España) | Русский | Türkçe

Author: iamkun
Source Code: https://github.com/iamkun/dayjs 
License: MIT license

#node #javascript #datetime #api 

Dayjs: Fast 2kB Alternative to Moment.js with The Same Modern API
Gordon  Murray

Gordon Murray

1652911740

Dateable: A Dart Package to Help You with Managing Dates Easily

📆 Dateable 

A Dart package to help you with managing dates easily. Can be used to store, format, convert, construct, parse and serialise dates. Calendar correctness is guaranteed by the usage of DateTime's system under the hood.

⚙️ Import

In your .dart files:

import 'package:dateable/dateable.dart';

⚗️ Usage

👷 Constructors

Variety of different constructors allows for great flexibility and interoperability with other types.

final date = Date(31, 12, 2019);
final date = Date.fromDateTime(DateTime(2019, 12, 31, 19, 1)); // Time of day is truncated
final date = Date.parseIso8601('2019-12-31T18:23:48.956871'); // Time of day is truncated
final date = Date.parse('31122019');
final date = Date.today();
final date = Date.yesterday();
final date = Date.tomorrow();

And a handy DateTime extension:

final date = DateTime(2019, 12, 31, 13, 26).toDate(); // Time of day is truncated

All of the above result in the same date object!

📅 Getters

There are three getters. Simple and easy.

final date = Date(11, 3, 2002);
print(date.day); // Prints 11
print(date.month); // Prints 3
print(date.year); // Prints 2002

↔️ Conversion methods

Date allows for seamless and easy conversions to most commonly used representations!

final date = Date(11, 3, 2002);
final dateTime = date.toDateTime(); // Time of day is set to zeros
print(date.toIso8601()); // Prints 2002-03-11T00:00:00.000
print(date.toString()); // Prints 11032002

📊 Comparisions

Comparisions work just like in your well-known DateTime objects!

final earlier = Date(11, 3, 2002);
final later = Date(21, 9, 2004);
print(earlier.isBefore(later)); // True
print(later.isAfter(earlier)); // Also true

On top of this, there are also operators > (is after) , < (is before), <=, >= and ==.

Here comes another handy DateTime extension:

DateTime(2002, 3, 11, 14, 56, 28).isTheSameDate(Date(11, 3, 2002));

But if all you want is to check if your Date is nearby, here you are.

final date = Date(11, 3, 2002);
date.isToday();
date.isYesterday();
date.isTomorrow();

📰 Formatting

You can format your Dates to Strings both with top-level constants and with String literals:

  • yyyy - 4 digit year, i.e. 1997
  • yy - 2 digit year, i.e. 97
  • mm - 2 digit month, i.e. 03
  • dd - 2 digit day, i.e. 11

Both of the below options are correct:

Date(11, 3, 2002).format([dd, '-', mm, '-', yyyy])
Date(11, 3, 2002).format(['dd', '-', 'mm', 'yyyy'])

🔨 Modifiers

Last but not least, there is a set of useful modifiers. Every Date object is immutable by default, so each of them creates a new Date object.

date.addDays(2) == date + 2 // Always true
date.subtractDays(7) == date - 7 // Also always true

You can also use the idiomatic copyWith function.

date.copyWith(day: 21, month: 9);

Sorting an Iterable of Dates chronologically is even easier:

[Date(21, 9, 2004), Date(24, 12, 2006), Date(11, 3, 2002)].sort((a, b) => a.compareTo(b));

Now the list is [Date(11, 3, 2002), Date(21, 9, 2004), Date(24, 12, 2006)].

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add dateable

With Flutter:

 $ flutter pub add dateable

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  dateable: ^3.0.0+3

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:dateable/dateable.dart';

example/dateable_example.dart

import 'package:dateable/dateable.dart';

void main() {
  // The most basic constructor.
  final date = Date(21, 3, 2002);

  // You can also use [fromDateTime] constructor...
  if (date == Date.fromDateTime(DateTime(2002, 3, 21))) {
    print('True!');
  }

  // ...or use an extension...
  if (date == DateTime(2002, 3, 21).toDate()) {
    print('Also true!');
  }

  // ...or parse from [String] ddmmyyyy...
  if (date == Date.parse('21032002')) {
    print('This is awesome.');
  }

  // ...or even parse from an ISO8601 [String]!
  if (date == Date.parseIso8601('2002-03-21T14:35:26.896')) {
    print('Very useful.');
  }

  // Do subtractDays and operator- have the same meaning?
  if (Date(1, 1, 2020) - 2 == Date(1, 1, 2020).subtractDays(2)) {
    print('Yes, they do!');
  }

  // The same with addDays and operator+.
  if (Date(31, 12, 2021) + 18 == Date(1, 1, 2022).addDays(17)) {
    print(':)');
  }

  // You can also use operators >, <, >=, <= and ==...
  if (Date(21, 3, 2002) < Date(21, 9, 2004)) {
    print('Spoiler: it is true.');
  }

  // ...as well as isAfter() and isBefore()!
  if (Date(21, 3, 2002).isBefore(Date(21, 9, 2004))) {
    print('This is also true.');
  }

  // Checking if [DateTime] is on the same day as your [Date]
  // is incredibly easy.
  if (DateTime(2002, 3, 11, 14, 6).isTheSameDate(Date(11, 3, 2002))) {
    print('A really nice extension.');
  }

  // Checking if the [Date] is today, tomorrow or yesterday is even easier.
  if (date.isToday() || date.isTomorrow() || date.isYesterday()) {
    print('The star is born.');
  }

  // You also gain access to [today], [tomorrow] and [yesterday] constructors.
  print(Date.yesterday().toString() +
      Date.today().toString() +
      Date.tomorrow().toString());

  // There are also some nice conversions:
  if (Date(21, 3, 2002).toDateTime() == DateTime(2002, 3, 21)) {
    print('Nice.');
  }
  if (Date(21, 3, 2002).toIso8601() == '2002-03-21T00:00:00.000') {
    print('Nice!');
  }
  if (Date(21, 3, 2002).toString() == '21032002') {
    print('<3');
  }

  // You can enjoy the copyWith function!
  if (Date(11, 3, 2002).copyWith(day: 21, month: 9) == Date(21, 9, 2002)) {
    print('Useful for short, idiomatic mutations.');
  }

  // Formatting is as easy as it gets!
  print(date.format([dd, '-', mm, '-', yyyy]));

  // Finally, due to the implementation of [Comparable] interface,
  // you can sort easily:
  final result = [Date(21, 9, 2004), Date(24, 12, 2006), Date(11, 3, 2002)];
  result.sort((a, b) => a.compareTo(b));
  print(result); // Prints [11032002, 21092004, 24122006]
}

🐛 Contributing / bug reporting

Contributions and bug reports are welcome! Feel free to open an issue or create a pull request.

Author: SugaR256
Source Code: https://github.com/SugaR256/dateable 
License: MIT license

#flutter #dart #format #datetime 

Dateable: A Dart Package to Help You with Managing Dates Easily