Sorry, guys, but these values just determine how dates and times are rounded up with the time script they're using.
e.g.
If something was 11 months ago, it would round it up to "a year ago".
If something was 26 days ago, it would round it up to "a month ago".
If something was 22 hours ago, it would round it up to "a day ago".
If something was 45 minutes ago, it would round it up to "an hour ago".
If something was 45 seconds ago, it would round it up to "a minute ago".
The same values are present in the base version of the script they included in the main shopify script.
The devs themselves have outlined why you don’t want to use it in a blogpost here and have since put it into maintenance mode.
Basically, the API has some unusual quirks and while it solved lots of problems for people for a while, there are now different and better libraries out there.
Nice list! Already used some of those tools in my smaller projects. I think one library is missing from your list: Moment.js (although most devs might already know it)
Working with dates is a real pain in the ass, especially with vanilla JavaScript.
Or Day.js as Moment.js is now considered legacy
Notes - Day.js is one of the recommend alternative to Moment.js which have the similar API to Moment
I'm not sure what is the issue you're having but I would not recomend using moment (https://momentjs.com/docs/#/-project-status/).
Personally I use date-fns, but there's other alternatives in the link above.
Great work, I really like the Sunrise/Sunset
May I suggest adding HH:mm:ss format? It will make numbers like 4:20:5 to 04:20:05
Libraries such as date-fns or moment.js have cool formatting features
They're just using an off-the-shelf library for it, likely Moment.js according to their acknowledgements page. It's not like Discord was purpose built to handle future times, they're just using a framework built for more general time and date handling.
In fact, it's probably <code>moment#calendar</code>.
Well, First off those if-else statements can be removed. There is no need for that since momentJS has .diff method to compare dates, so essentially you could say:
diffDate = startDate.diff(enddate)
do a switch/case and viola cleaner, less code.
This is just top of my head but: https://momentjs.com/docs/#/use-it/ Is super well documented!
Dates are weird. Like /u/Meefims said, you're calculating for 28 days, while a month can be anywhere between 28 and 31 days (and varies based on if it's a leap year). Unless you're really trying to save space, I'd suggest using moment.js for this, as they've already figured out all of the edge cases.
Create a duration, then use .asMonths()
to get the number of months. Something like moment.duration(moment(dt2).diff(moment(dt1))).asMonths()
In vanilla JS you instantiate a date:
const date = new Date();
Then
date.setDate(date.getDate() + 1);
But this is kind of ugly and only works if you want to increment that specific variable.
If you're going to be working with dates a lot and want something more comfortable to work with check out MomentJS. It's a really solid date library with all kinds of manipulation and formatting capabilities and very comfortable syntax.
Then you can do stuff like this:
moment().add(7, 'days');
And even assign the new value to another variable without changing your current one.
I mean, once upon a time, sure, but for a good long while now Moment's own docs have officially recommended that you use something else instead: https://momentjs.com/docs/#/-project-status/. Chrome's built-in dev tools show warnings if you audit the JS of a site using Moment: https://twitter.com/addyosmani/status/1304676118822174721.
Part of the reasoning in Moment's doc there specifically references of Moment's size & general bloat, when compared to other modern libraries that support tree-shaking and offer fine-grained control of what you're importing. Lots of other good reasons in there too.
I think date-fns is the main candidate, with none of the downsides, zero dependencies, and a similarly high level of mature stability - the first release was 7 years ago, and (according to npm stats) it's well on the way to overtaking moment in real-world usage as well.
Fabienne: Whose date framework is this?
Butch: It's a library, baby.
Fabienne: Whose library is this?
Butch: It's Moment's.
Fabienne: Who's Moment?
Butch: Moment's dead, baby. Moment's dead.
JavaScript can't do it. See Date object reference.
Of course, in JavaScript you should be using moment.js, or if it's too heavyweight for you, XDate. (I use XDate myself in a Node.js server I develop.)
I doubt that you actually need to know more than 20% of this "roadmap" to start being efficient with React, but I wouldn't recommend <code>Moment</code> in 2021.
Use 'S' to format with a fractional second. And 's' for seconds.
Then, adapt accordingly to your " setOpenTime" function
.format('hh:mm:ss.SSS A') = "12:18:09.778 PM"
​
I made a New Years countdown timer with moment and Vue. You can check out the codepen here. Like u/earthboundkid said, a computed property isn't really a great choice for this because there's nothing to trigger a recompute of the value as the moment object isn't reactive.
I just set up an interval on mount of the component that runs every 250ms (though this could probably be a little longer). It uses moment's diff function to determine the time remaining until the deadline, uses that to create a new moment object, and then formats it with a custom format string. It's also important to clear the interval when the component is destroyed, so it doesn't keep running once it's not needed.
If you really don't want to install anything: (Date.now())[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now] Gives you the number of milliseconds passed since 1970/01/01 00:00:00 UTC. You can get that value when saving your article and put it in the db (or wherever you store it) next to your article content. When you show your article and load your article-data (creation datetime and content), parse the date(time) from the milliseconds and display it.
If you don't care to use a small library: (moment.js)[https://momentjs.com/]. Same principal as above but somewhat easier to use. moment().toISOString() will give you a nice string representation of the current datetime. Save it along with your post and afterwards when you want to display it, it's as simple as
moment(savedDatetimeArticleCreationISOString).format("YYYY/MM/DD HH:mm:ss") for example.
moment.js documentation can help you with that, especially .day() method:
if (Meta.currentUserTime.day() !== 3) { // put skip event here }
there's also .weekday()
but i don't recommend using it as first day can be Sunday or Monday depending on locale and may provide inconsistent results.
.isoWeekday()
is fine I guess, the difference from first one that Sunday is 7 (not 0),
The problem is that when summer time ends, 02:59:59 CEST ticks over to 02:00:00 CET (for example) and the hour 'repeats'. It's impossible to unambiguously determine DST based on local date/time alone during that hour, the value "02:30:00" could be either.
According to the moment.js docs:
>Moment Timezone handles this by always using the earlier instance of a duplicated hour. [...] You won't be able to create a moment with the later instance of the duplicated hour unless you include the offset when parsing.
OF course for this example usecase one may well argue that not being able to make a booking with a check-in happening during one specific hour in the middle of the night once a year is perfectly acceptable, but for other applications it may not be.
The time objects it provides are from Moment.js: https://momentjs.com/docs/#/displaying/days-in-month/
So it should be something like
Meta.currentUserTime.daysInMonth(); or
Meta.triggerTime.daysInMonth();
You can add an event listener to the input
JS
// sample.js
var input1 = document.getElementById('date-1'); var input2 = document.getElementById('date-2'); var result = document.getElementById('result');
var date1; var date2;
var msPerDay = 24 * 60 * 60 * 1000;
input1.addEventListener('change', function(e){ date1 = new Date(e.target.value); date2 && calculateDelta(date1, date2); })
input2.addEventListener('change', function(e){ date2 = new Date(e.target.value); date1 && calculateDelta(date1, date2); })
function calculateDelta(d1, d2) { var daysLeft = (d1.getTime() - d2.getTime()) / msPerDay; result.innerHTML = daysLeft + ' days'; }
HTML
<!-- index.html -->
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <label for="date-1">Date 1</label> <input type="datetime-local" id="date-1"/>
<label for="date-2">Date 2</label> <input type="datetime-local" id="date-2"/>
<p id="result"></p> </body> </html>
For more information about date parsing, you can check out the Date object or you can use a library like momentjs
Is it important to retain the time zone on the server, or are you just using that to display the time in the user’s time zone? If you need to know that a particular time is in, for example, America/Chicago
, you might want to store it in a separate field.
To communicate times, I normally use ISO 8601, which is easy to validate with <code>Joi.date().iso()</code>.
If you need to validate a time zone field as well, you could build a whitelist with something like (untested) <code>Joi.string().valid(moment.tz.names())</code>.
Version 1.0.1 fixes your problems!!
You can now manually set any language code (like "en-GB" for English, or "hr" for Croatian) in the settings, to change the language and formatting of the date. If you'd really like to get your hands on things, you can completely replace the date display with a format string, based on the MomentJS formatting rules.
I hope this update proves useful for you!
The way we format times is based on locale, hence why it's tied to the language you use. You can see a demo here: https://momentjs.com/ - English (United Kingdom) is 24h clock whereas, English (United States) is 12h clock.
Time zone changes are captured by the JavaScript library I am using, Moment.js. Changes will be captured by my site by updating the library and redeploying a new, updated version. the times are stored on the server as a time+timezone so when viewing the old event on a new, updated version, the change in time zone will be correctly accounted for by Moment, for times before and after the change alike.
I just said what input I used. Basically, I gave it a time that "doesn't exist" ... at 2am, the clock jumps ahead to 3am, so there is no 2:30am that day.
The other boundary to check with DST issues is the day it ends. DST means there are 2 1:30ams.
It's basically this: https://momentjs.com/timezone/docs/#/using-timezones/parsing-ambiguous-inputs/
tl;dr for people: don't schedule events for this stupid time.
Are you allowed to make use of third party / open source libraries when building your project? For something like this, one of the most annoying parts will most certainly be dealing with all the days and months. One library I've used in the past is Moment.js which made my life 100x easier when dealing with dates, I'd highly recommend integrating something like that into your project if you're allowed.
With the conversion and general handling of dates out of the way from a library like that, you can focus your efforts on the design and storing events in a database. You seem to have experience in all the basics needed to throw together a quick web project...For example, Boostrap for the front-end and a simple PHP back-end that stores events in a MySQL database.
>Look into lodash
Which parts of lodash do you think should be added to the "standard library"? (also, what is your definition of JavaScript's "standard library"?)
> and moment
Great example, JavaScript's Date
object is sorely lacking.
By bringing up Moment, I'm guessing that you support the blog author's position that the "stdlib" should be small?
Moment's project status page indicates that it is a "legacy project in maintenance mode", which makes me glad that it wasn't added to the "standard library" because then it could never be removed.
> Also the whole “fetch” debacle.
I'm not familiar with this, what was it?
I appreciate the Date
example, whenever this topic is brought up I always ask people what's missing from JavaScript's "standard library" (and what they define that to be), and people rarely list anything concrete.
> moment or any other time utility lib
I'd probably recommend looking at another library; moment is old, bloated and doesn't work well with tree shaking. Even the moment devs recommend looking at other alternatives such as Luxon, dayjs (if you're used to moment syntax) and date-fns.
Other than that, typescript is a given and material UI seems like a safe choice. Depending on the requirements from the clients I might ditch axios and redux for something else. The fetch api is good enough for most cases, and with the Context, Reducer and Effect hooks provided by React I can do most things I need from redux. So if for example my client wants to have charts, I'd ditch one of those in order to install a charting library.
this can be done with the core plugin templates.
to use
---
personally i use it with a template... if you are using a template, {{date}} or custom format {{date:YYYY-MM-DD}}. when a note is made from a template using these, the date will be filled in on creation.
Those codewars challenges will be a great start - you'll really start to level up when you couple that with applied experience. In other words, taking some of the logic stuff you're learning, and using it to build something helpful on your own.
The plus side is that you'd be really hard pressed to think of a program you can write that doesn't involve some level of applied logic. Maybe try writing an app which tells you what the current time is in a bunch of different time zones. Write it first using the date-fns or moment libraries, and then try to use less and less of the functions provided by those libraries, replacing it with your own code. You might be surprised how tricky and involved just that can be!
Meta.currentUserTime is based on moment.js. All the documentation is here.
You will want to take what google calendar gives you and load that into a separate variable. Look into using moment.parseZone (or moment.tz but I think parseZone will do it for you).
Once you have another variable with the calendar time you can query for before, after, etc. comparisons.
Careful with time comparisons -- make sure that the moment objects (meta.currentUserTime and the calendar) are using the same timezone otherwise you'll run into issues.
If the above doesn't help let me know and I'll work out an example.
>const moment = require("moment");
You should probably replace moment (see: https://momentjs.com/docs/#/-project-status/) with another an alternative in the link provided (scroll down a bit).
It's tiring, but I'm more tired of left wing and center media talking about it than right wing media (mostly since I'm more likely to agree with them).
Not just media, the left wing culture war is all over the place. I'm reading documentation for a javascript library we use at work, and there's messaging about what political causes I should donate to? I'm trying to do work here.
Firstly, moment is depricated and probably shouldn't be used anymore.
A popular replacement is date-fns.
A particular tool it includes which might help you out is formatDistance.
In their docs they have a list of alternatives https://momentjs.com/docs/#/-project-status/recommendations/
I have used dayjs and liked it.
Can't wait for Temporal to be finalized though. Will be nice to have a native datetime library that doesn't suck to use.
Not sure if this is exactly what you are asking but moment.js is an extremely popular library for parsing, formatting, displaying dates... quite a bit more flexible than the native Date object IMO.
Going to need more to be sure, but local()
changes the time displayed from UTC to local (if it was in UTC).
That would explain the difference in time between the two. If you give code of how the moment is created it'd be easier to tell though
Javascript has pretty bad support for parsing date strings in a specific format. You might have some better luck with a library like moment.js. Here's a more relevant part of the docs.
If you don't want to use a library, you should be able to parse the string yourself as long as you know what format it's going to be, and create a date object off of the parsed month, day, year, etc.
If you can use Moment.js you could do something like:
const differenceInMonths = moment(putYouracquisitionDateHere).diff(moment(), 'months');
There's probably also a way to do this in plain JavaScript, but it will be a bit more complicated.
worth considering that the working week differs across the Globe - in case this impacts the "available/allowed" days for sending messages.
For example: whilst in Europe & Americas offices tend to be open Monday-Friday, in the Gulf (e.g. UAE) the workweek runs Sunday-Thursday.
Mention this as it could have implications on how you store available days, or the logic used to confirm that 2 users can send messages during "allowed times/days".
--//--
You could explore the use of `Luxon` as DateTime library offering handy functions + built-in support for time zones. See: moment.github.io/luxon
Another could be https://momentjs.com/timezone/ = immutable API, chainable, and built-in time-zone support.
It's not deprecated. It's in maintenance mode. They are just not adding any additional features but they will keep supporting the library and fixing any critical bug.
As mentioned already, you can see if new Date(your_maybe_date_string)
comes back with a valid date object, or you can use a library.
That said, I would not use moment.js. Check out this advisory from the moment.js team: https://momentjs.com/docs/#/-project-status/. They are essentially deprecating the library, and they offer a list of more modern alternatives.
First thing first, you need to get the value of the currentUserTime
. Lets say you need hours, then it will be Meta.currentUserTime.hour()
. This will be a variable containing a number.
On the other hand, SunsetAt
property is a string (as it returns a full timestamp containing hyphens). You first need to format that string to only display the hour. That's why you can't compare between them two (number and string).
To fix that, use .toString()
method applied to your CurrentTime
variable so you parse it as a string type and then you can compare.
---
let currentTime = Meta.currentUserTime.hour().toString(); //get the hour and parse it like a string. let sunsetTime = moment(Weather.currentWeather[0].SunsetAt, 'YYYY-MM-DDTHH:mm:ss').format('HH'); //get the sunset timestamp then format it to only hours.
if (currentTime < sunsetTime) //we can now compare as both variables are now string types. IfNotifications.sendNotification.skip(); else Do something;
hour value varies in 0-23 range. IFTTT uses moment.js - very powerful library for operating with time. To check if current time is in certain range you can do next check:
const condition: boolean = Meta.currentUserTime.isBetween( Meta.currentUserTime.hour(5).minutes(30), Meta.currentUserTime.hour(10).minutes(30) ); if (condition) { Aaa.bbb.skip(); }
.isBetween(afterDate, beforeDate)
- returns true if time between two provided date arguments.hour(5)
- if used without argument returns current hour, with argument returns date with modified hour value, same for .minute(30)
More info you can find on moment.js website.
I think that's doable with using query feature, before adding code add Wyze -> History of Contact Sensor closes to the applet. The filter code will look next way:
const lastTriggerTime = moment(Wyzecam.historyOfContactSensorCloses[0].TriggerTime); if (Meta.currentUserTime < lastTriggerTime.add(30, 'seconds')) { IfNotifications.sendNotification.skip('30 seconds cooldown'); }
How it works: to time of last trigger from query it adds desired delay (you can set different ofc, more info here). If it falls in 30 seconds gap - skips the notification.
The tech stack you have planned seems great, moment js should be replaced though. They even advise this on their website. https://momentjs.com/docs/#/-project-status/. For state management take a look at zustand it's a real simple way to add state into your project if you don't want the bloat of redux or flux etc
Huh, I thought it returns string like this September 19, 2020 at 09:52AM
, but if it's like in your case, it's even better.
Filter code ships with moment.js, which allows both to parse and format the date string. You can try something like this:
const lastSunset = moment(Weather.historyOfSunsets[0].SunsetAt); if (lastSunset.hour() < Meta.currentUserTime.hour()) { // after sunset } else { // before sunset }
but comparing just hours may be bad idea, would be good to add minutes as well:
const lastSunset = moment(Weather.historyOfSunsets[0].SunsetAt); const minutesFromMidnight = function (date: any = undefined) { return moment(date).diff(moment(date).startOf('day'), 'minutes'); }; if (minutesFromMidnight(lastSunset) < minutesFromMidnight(Meta.currentUserTime)) { // after sunset } else { // before sunset }
I think there are two issues here. The first is that to parse a string with momentJs you must include a date. The library expects a valid ISO 8601 string which must be composed from the least to most specific date/time element(i.e. you can have year-month and leave out day-hour-minute etc, but you cannot start with the hour, leaving out year and month and day).
Additionally the moment function does not take both the string to parse and the format as arguments. The string is used to instantiated the moment object and then format is called on the resulting object, just like add, when you want to return a newly formatted string.
So for your purposes you would want to do something like:
To start with "now" simply use:
var time = moment()
To start with "10:00am" specifically you need to use a date:
var time = moment(2020-07-26 10:00am)
time.add(5, "hours")
console.log(time.format("HH:mm"))
Note that "HH:mm"
will give you the hours in military time so this will be "15:00"
To read "3:00" use "hh:mm"
This page may also be useful.
Hope this helps!
There is a java library that you could look into
https://momentjs.com/timezone/
I'm sorry I don't have time now to check it out. But I have used it in the past and it was working fine. I'll hunt out the project and I was working on and see if I can resurrect it.
The simplest option would be to use the datetime.strftime method to convert the current time into a string inside your route - you can format this string however you wish. You then pass this string to the Jinja template and render it in the HTML.
from datetime import datetime
## In your route...
now = datetime.now() # current date and time date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
return render_template('date-time.html', date_time=date_time)
## In your Jinja template...
<p>The date and time is: {{ date_time }}</p>
A slightly more sophisticated option is to use moment.js (there is a flask-moment extension) which allows you to do the formatting in the Jinja template. A nice feature of this is it allows you to localise the display of the date and time to account for local preferences and timezone. The downside is you need some javascript in your html, though the extension handles this. Once setup you would pass the datetime object in render_template and then have something like this in your Jinja template:
<p>The date and time is: {{ moment(now).format('LLL') }}</p>
I would get the timezone that you want to display (the server in this case), and then use a library such as momentjs to do the conversion from from the local client tz to the server's tz.
I always struggled with date comparisons in JS/GAS. I'd recommend creating a library with Moment.js: https://momentjs.com/ (get the code from their GitHub). You can import the library into any of your projects and it provides amazing functionality for handling dates and makes your life so much easier
Not pretending. Timezones are easy to handle.
Each client see the time in a local format.
This has been a tricky one for me as well and I've used formulas to resolve this:
IsDueThisWeek
formatDate(now(), "WW") == formatDate(end(prop("Due Date")), "WW")
It uses formatDate to extract the numerical week of year for "now" and the end day of a date range property named "Due Date" or the date itself, if it is not a range. This page has other examples of date formats you can use in this formula:
https://momentjs.com/docs/#/parsing/string-format/
The caveat is that if that if DueDate is a range, it won't tell you if it is due within the range of the due date... only if today is within the last week of the range.
If you're looking for date manipulations with a few clicks... Take a look at the moment.js. Most conversions are one line.
I subscribe to AutoTools (well all of them), but I found that most of the functions are just wrappers for JavaScript. There are times that it's harder to troubleshoot a plug-in vs your own code. The library below, you can go under the hood of needed too. Also, way more support for Javascript than Tasker. Only a few of us actively post replies to Tasker and we all have out preferences.
I wouldn't know how to help you with the date issue except via Javascript, since I'm not sure how AutoTools works under the hood. Best of luck.
Easiest... Download the moment.js library to your device and do it in Javascriptlet. It'll be one line of code using that library. The front page of the library has many examples.
Library path would look something like this (depending on where you save the library):
/storage/emulated/0/Tasker/javascript/moment.js
var getFormattedDate = new Date()
.Date
class isn't very good. Moment.js is more full-featured, and has the method you want.In JS, "classes" are really just functions. So Date
is a function. Functions are also objects. So now
is a property on the object Date
. But functions are also values. The value of Date.now
is a function which takes zero arguments. You can (but should not) glue your own functions onto Date
. e.g.
Date.nowAsDate = function() { return new Date(); }
val someDate = Date.nowAsDate();
JS use integers for internal representation of time (milliseconds since UNIX Epoch). Timezone is added only when you convert date to human readable string or when you use methods like getHours
or getMonth
(and there are UTC alternatives for this methods: toUTCString
, getUTCHours
, getUTCMonth
, etc). So if you use only integer form, you should be safe, but...
But there is another big problem with time in JS - if user has wrong configuration of system clock (instead of using correct timezone, clock is set to +2 hours ahead), you can get quite strange results.
Libs like moment.js can help with managing time and different timezones and locales, but system clock must be properly setup.
The FTL started date is calculated by running ps -p {PID} -o start
. Looking through the code briefly, it looks like the query date/time may be coming from this line of code which is using moment. If you go to moment.js does it display the right time on the site for you? Or is it the same time you are seeing in PiHole?
Yeah, I saw all of that. I'm not working through his course, so I opted not to extend bootstrap/base. Instead, I called the js file directly from my base.html:
<!-- Scripts================================================= --><script src="
<code>https://momentjs.com/downloads/moment.js</code>"></script>
(I also tried downloading the file, and url_for() directly to the static/js folder, but that also didn't work.)
From there, I initiated the app in my __init__ file:
from flask_moment import Moment...flask_moment = Moment(app)
When I refresh my page from here, I can see the javascript file is being served. From there, I'm using this code in my HTML template to call the timestamp:
<!-- Post Timestamp================================================= -->posted: {{ moment(post.datetime_posted).calendar() }}
When I reload the page, it reloads with the js file still served as shown under resources, but nothing populates after 'posted:'
Most projects today will use React, Angular or Vue as a "baseline". Because you'll immediately reap the rewards from using a framework. It helps you to break it down to smaller pieces, or "components" as we call them.
React, Angular and Vue are the three biggest out there, I'd recommend you to test all three, just build a simple "ToDo" app with all three, and you'll get the feeling for what components are and the differences in the frameworks. See which syntax fit's you best
There are tons of other smaller ones, but that's only when you're feeling a bit advantageous. Stick with one of the three to begin with :-P
--
As for other libraries, they are like plugins. There are tons of different ones out there, maybe even hundreds that accomplish the same thing :-D
It's up to you to find what suits your needs best. An example: For the longest time, when I needed to do something with dates, my go to library would be moment.js. However, lately, there's other libraries that accomplish the same thing in less kilobytes, like day.js. Which quickly has become my new go to library when working with dates.
You decide yourself if you want something mature, that's been battle-tested for a decade like moment.js or something that has a lot smaller footprint, but might not be as mature yet. Like day.js.
​
There's no silver bullet, you have to try em out and see what fits your needs :-P
--
RxJS brings reactivity to React, just like Vue and Angular has built-in
Sorry to say that I havent had time to fully understand the function myself. So I don't have an answer for you. I did find an library that does exactly what you want. It's called momentjs.com
>That is just about the fastest way to annoy a programmer.
Maybe a newbie programmer, sure. Anybody with a bit of experience knows that you DO NOT MESS WITH TIMEZONES YOURSELF! Always use libraries or built-in methods to work with timezones. They thought of way more edgecases than you can ever account for. https://momentjs.com/ is a great one for javascript. (Inb4: but moment.js is slow, you can use 'x' to do it faster! — unless you're building an application that handles hundreds or thousands of datetimes at a time, the difference is negligible.) This site does use moment.js (but they bundle it with their own javascript file for some reason? I guess it saves on requests but it loses on caching\loading only parts you need for a specific page)
You can perform all of this using the build in Date methods.
I would suggest looking at the getDate
, getMonth
, getFullYear
, getHours
, getMinutes
, getSeconds
, etc. All of these will return local time (based on your Operating System's time zone, and sometimes browser interpretation of that).
If you want these values to always be in UTC, then you can use the UTC equivalents, found in the same spot in the documentation linked above. If you're dealing with time zone differences, it might be best to always store dates in UTC, and then let the browser convert to the users local timezone.
As another user said, if you're going to be doing a lot of date formatting, converting, parsing, etc., it might be best to look into moment.js, which helps immensely with dates in JavaScript.
You could possibly look into using Moment.js. It has a specific functionality where it attempts to guess the user's timezone. For my uses this has proven to be fairly accurate, but there's always going to be an air of uncertainty. From here you could attempt to map a timezone to a country.
Documentation: https://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/
Ah, you're kidding right? I'm struggling to find a single modern language that doesn't have a built-in internationalized Date/Time library and/or multiple 3rd party ones.
Like the client would use JS for something like this, https://momentjs.com/, it wouldn't take a CS student 5 minutes to figure out how to properly format dates according to region using Moment.js.
> Plus, moment does not provide a text based representation of relative dates afaik.
Not entirely sure I understand you correctly, but perhaps you mean this? https://momentjs.com/docs/#/displaying/fromnow/ (and related functions)
It is a pretty powerful library with a lot of functionality.
>I even still have no idea which one of these dates function that i have to use, new Date () ? new Date().toString() ??? Or sometimes new Date().toISOString() ?????
Well, do you want a Date object, a string representation of a Date object, or an ISO-standard string representation of a date?
The toString
functions are there so you can display a date, not so you can manipulate it. A Date
is an object, new Date().toString()
produces a text-based representation of that date.
For comparing dates, you can use the getTime
function on Date
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
That will convert your date into the number of milliseconds since 1/1/1970 00:00 UTC. So you can subtract one date's time from another date's time, and get the number of milliseconds difference between them. From there, it's a simple set of conversions: 1000 ms per second, 60 seconds per minute, 60 minutes per hour, and 24 hours per day. Simple math.
If you want something with a simpler API, the gold standard for date libraries in JS is <code>moment.js</code>.
You can definitely make a web app to do this. Then it'd be easily accessible from anywhere. Take a look at this.
You'd need a small bit of HTML/CSS but mostly JavaScript. But in all honesty, the entire program would be just a few dozen lines so you wouldn't need to learn the entire language if you didn't want to.
Not sure how accurate: https://github.com/infused/ziptz
Moment.js detect timezone (by browser): https://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/
Other than that you can also build your own list of zip codes per state and classify each state timezone. Doesn't always work when you want to be super accurate, cause there are always outlier cities/counties. Timezone is a tricky thing.
No worries. You could use moment as an alternative, https://momentjs.com/ and do something like
javascript
moment('Thu Mar 14 2019 15:30:00 GMT+0000 (Greenwich Mean Time)').format('LT');
Documentation is pretty good for it getting different formats is really easy.
If you need to work with the dates and times, I recommend using Moment to handle parsing, manipulation, and formatting. They've taken care of lots of edge case stuff, like date addition/subtraction when you are working between daylight saving time and standard time.
let date = moment.unix(var2); let dayAfterDate = date.add(1, 'day'); let formatted = dayAfterDate.format('YYYY-MM-DD');
​
My pet peeve w/ moment.js is how it handles string parsing, falling back to browser-specific heuristics if it doesn't conform to ISO 8601.
This was in the docs for vue-moment:
>duration is for contextless lengths of time; for comparing 2 dates, use the diff method rather than hacking around with Moment durations. For more information about moment#duration, check out https://momentjs.com/docs/#/durations/.
​
Perhaps try Vue.moment(eventDate).diff(now, 'days')
The name for the format 2018-08-01T17:30:00+00:00
is RFC 2822, but support for it is a little inconsistent. Don't rely on it.
The same goes for JavaScript dates as a whole. They're just a bit flaky and weird. I don't normally recommend libraries on here when they're just a wrapper for built-in JS functionality, but Moment.js is what we all use in the wild because it's just so much nicer than the JavaScript Date object.
DateTime library for android that can parse a string without specifying a format? Iam making a rss app and every xml has a different date time representation which is so frustrating. Something like moment.js in js.
(sorry for the rushed answer, headed out the door) Not exactly sure what the objective is, but have you considered using a unix timestamp?
Also, if you aren't familiar with moment.js, I suggest having a look at that to help with date manipulation.
First of all, store date time as ISO8601 (string) values. Don't ever store datetime values as anything else (OK, well, maybe UNIX timestamp format...sometimes).
Then, use momentjs to ingest your ISO8601 string values to moment objects, then use moment's comparison operators to build whatever filter and sort mechanisms you want.
If you can't use standard values, you could still use momentjs to ingest your strings and then perform appropriate sorting/filtering operations.
Moment.js can handle all of this pretty easily.
First, you'll need to convert the date and time to a moment object. I'd handle this all in the service in which you are getting your data.
It will look something like this:
var dateTimeMoment = moment(dateTime.date + ' ' + dateTime.time, 'M/D/YYYY h:mm A');
To get the time ago, you can use the fromNow() method included in moment.js.
var timeAgo = dateTimeMoment.fromNow();
Moment will automatically determine the unit of time to display when calculating the time difference using something called relative time thresholds. In this case, since the time from now was greater than 26 days ago, it is displayed as months. If you want to customize these thresholds, say always display in 'days ago' until it is more than a year ago, you'd just need to add a line of code to set the new threshold:
moment.relativeTimeThreshold('d', 365);
Here is a fiddle illustrating the solution to the specific datetime object you provided. Just loop through your array and apply the same process for each item.
I noticed that, and this should be correct? you are confusing me :)
moment().add('seconds', 1); // Deprecated in 2.8.0 moment().add(1, 'seconds');
Before version 2.8.0, the moment#add(String, Number) syntax was also supported. It has been deprecated in favor of moment#add(Number, String).
You can combine the time and event params and end up with "?event=MyFunEvent&ts=1500445136"
Use moment.unix(1500445136) to get it back into a usable format.
Moment.js does all the time calculation heavy lifting for me. It should be pretty much exactly correct with respect to daylight saving, time zone changes, calendar updates, etc.
Nice. I think the reason why useful date time functions are not baked into JavaScript is because it would bloat it more, and we have moment.js anyway (which supports adding weeks too):
I've built a booking system before. I turn "Monday @ 5:30pm" into two things for the database:
Date
(just leave it in the user's timezone)"America/New_York"
Then I use http://momentjs.com/timezone/ to convert a booking into an offset timestamp.
User 1 might choose "Monday @ 5:30pm", but User 2 in the next timezone over needs to be able to see "Monday @ 6:30pm".
I don't remember the exact mechanism. I think I used #2 so that I could display "Monday @ 5:30pm" in a drop-down/select box, send "Monday @ 5:30pm" to the server with the user's timezone, and then convert it on the server with https://momentjs.com/timezone?
I still have that project on my computer, so I would have to look.