Date and time without timestamp in Javascript - javascript

In Javascript I need to work with the concepts of date, time and "date and time " without referring to a particular point in time. This is exactly the same semantics that joda time's LocalDate and LocalTime provide in Java. I've been briefly looking at Date.js and moment.js, but both libraries seem to build on the Date object, which represents a point in time. Is there any javascript library that provides what I need?
Use case:
There is a model entity -a coupon- which has an expiration date (joda time's LocalDate). I want to compare that date with today's date, so I need a representation of today's date (actually a string in yyyy-mm-dd format would do). I know that today's date, and hence the result of the comparison too, will depend on the timezone settings of the browser's but that's not a problem.

I've started a few times on a JavaScript library with similar API to Noda Time / Joda Time / Java 8. I definitely see value in that. However, there's nothing out there as of yet, as far as I know. There are other reasons that make the Date object less than ideal. I'll try to remember to update this post when/if I ever get a new library off the ground, or if I learn of one created by someone else.
In the mean time, the easiest thing would be to use moment.js:
var expDateString = "2015-06-30";
var exp = moment(expDateString, "YYYY-MM-DD");
var now = moment();
if (exp.isAfter(now))
// expired
else
// valid
You could also do this with plain JavaScript, but there are some gotchas with parsing behavior. Moment is easier.

Related

How to convert a date object representing a point in time to a date object representing a day with zeroed time parts in moment.js

I need to represent date in the format 2021-11-21T00:00:00+00:00 but I get 2021-11-21T00:00:00+05:30. Please help me with this
moment('2021-11-21').format(); //2021-11-21T00:00:00+05:30
I had a similar problem when dealing with dates and birthdays in Golang, but this also applies to Javascript, I'd say. You should not try to use a date object for this task, because you can never fully rely on that when a clients browser is set to a different time zone. I ended up creating a date object myself, consisting only of 3 integers for day, month, year. By doing so you can be sure that time does not play a role at all.
By the way, this might be of interest to others as well: I did some research on how birth dates are handled in general, because when you think about it, your birthday is actually a point in time, so your birthday could change to the previous or the following day, if you look at it from a local perspective. I found out that birthdates (or dates "in general") are not considered as a time or datetime, only the year, month and day are important and they are always the same, regardless of the place/timezone you were born and regardless of the timezone the client lives in.
Instead of using moment, you can use moment-timezone and set it to GMT-0.
var moment = require("moment-timezone");
const time = moment().tz("Etc/GMT").format();
console.log(time);
And the result is something like:
2021-10-26T11:39:15Z
So I think you can't do that (except manually remove the 'Z' and add the +00:00) part as an extra string.
All dates are represented in your system local timezone. This means that moment('2021-11-21') is midnight of November 21st in your timezone (2021-11-21T00:00:00+05:30). If I run the exact same method then it will be local for my timezone (2021-11-21T00:00:00-06:00). If you need this to be in a specific timezone, or in GMT, then you probably want to use moment-timezone and cast the date to that timezone.
moment('2021-11-21').startOf('day').format()

The date 2019-04-01T00:00:00.000Z gives me previous month (March, not April)

So, I have the 1st day of month as 2019-04-01T00:00:00.000Z
When I use moment(date).month(), it returns me 2, not 3.
So, I receive March, not April.
What is the problem with it, and why I receive the previous month from the date? Maybe the problem in the TimeZone? Because my TimeZone is GMT-4, so, maybe this is problem?
Should I use UTC or ISO string instead to work with the date?
Like you mentioned, your timezone is GMT-4. The date that you are providing is in UTC. The 'Z' at the end stands for Zulu time, which is the same as UTC.
momentjs will convert this to local time.
How to handle this all depends on what you need the date for.
If this is a date that you saved somewhere before on a server, it might be important to add the correct timezone to it when you are saving it.
Be careful if you let a server create these dates, because the server might be running in a different timezone than your client.
If you create a new Date() in JS it will return a date object with the current time of your local time. If this happens on a server that's running in a different timezone, or in UTC (for example Docker containers), it will create a date in that timezone.
The best way to solve this is to think about your exact use case.
There are tons of articles written about handling dates and it's not easy.
If you have some time, this podcast helps to explain how dates work and will help you to get a better understanding of dates in general:
Coding Blocks - Why Date-ing Is Hard

Working with Time and TimeRange in Javascript

I'm starting a new project today. The application is a rewrite of an existing workscheduling application. The application works extensively with Times and TimeRanges.
Time: 08:45, 17:32, ...
TimeRange: from 08:45 till 17:32
I started looking for a library that handles the plumbing for me with this kind of data, eg: Earlier than, later than, in between, etc. I found moment.js and date.js immediately. I feel however that these libraries are more concerned about a certain point in time (a JS Date object) rather than the above described notion of Time and TimeRange.
Does anyone have experience working with Time and TimeRange as I described above in a JavaScript environment? What library could be useful for this?
You can use Date object to compare dates. You can construct 2 dates and then compare using usual operator.
For an ex:
var date1 = new date();
var date2 = new date();
Then compare like date1.getTime() == date2.getTime() or whatever you want to compare.
Hope this will help you.
Have another look at Moment JS, it's probably what you need. It has a rich library of date handling functions, and uses Duration objects to represent time ranges.
http://www.datejs.com and http://momentjs.com are the best as far as I'm concerned. A few more are listed here: http://codegeekz.com/6-javascript-date-libraries-for-developers/

Asp-net web api output datetime with the letter T

the data in the DB look like this
2011-09-07 14:43:22.520
But my Web API outputs the data and replace the space with the letter T
2011-09-07T14:43:22.520
I can replace the letter T with a space again in jquery, but can I fix this problem from the Web API (make the web api output the original data?)
I also do not want the miliseconds at the end. How can I get rid of them?
The format of how you see the date in the database is usually irrelevant, because it should be passed into .Net as a DateTime - not as a string. (If you are storing it as a varchar in the database, you have a bigger problem.)
ASP.Net WebAPI is returning the value in format defined by ISO8601 and RFC3339. This is a good thing, as it is a recognized machine-readable format. You probably don't want to change it.
If you really want to change it, you would need to implement a custom JSON.Net JsonConverter, deriving from DateTimeConverterBase. This is discussed here and here.
But instead, you should consider how you are using the actual result in your client application. You mentioned jQuery, so I will assume your consumer is JavaScript. In many browsers, the ISO8601 value that you have is already recognized by the JavaScript Date constructor, so you might be able to just do this:
var dt = new Date("2011-09-07T14:43:22.520");
But this won't work in all browsers. And Date doesn't have a whole lot of flexibility when it comes to formatting. So instead, you might want to consider a library such as moment.js. With that in place, you can do this:
var m = moment("2011-09-07T14:43:22.520");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // output: "2011-09-07 14:43:22"
Please note that the format string here conforms to moment.js, not to .NET. There are differences in case sensitivity. Please refer to the moment.js documentation for details.
One other thing - since the value you provided doesn't have either a Z at the end, nor does it have an offset such as -07:00, then I assume it came from a DateTime whos .Kind value is DateTimeKind.Unspecified. You should be aware that when this gets sent into JavaScript (or anywhere else for that matter), there is no information about what time zone is represented. JavaScript will assume the local time zone of the browser.
If that's not what you had intended, then you need to store UTC values in your database, and make sure they have DateTimeKind.Utc so they get serialized with a Z at the end. JavaScript will normalize this to the browser's time zone, but you will still be talking about the same moment in time.
Alternatively, you could use a DateTimeOffset type - which would serialize with the specific offset. JavaScript will still normalize this to the user's time zone.

Convert timestamp with specified offset for timezone with Date();

I've been digging through as many things as I can find, and I can't seem to find what it is I am looking for, so I am coming to the conclusion that I either don't know what I am looking for or its not possible. Either way..
What I am trying to achieve is taking a timestamp example: 1373439600000 and a given offset of -12 to 12 (is that correct, as far as range goes?) so I can then take that timestamp above subtract from it accordingly, and pass that new timestamp to the Date() function so I can then manipulate it for human readable display.
The offset is two part, It is user specified in one instance while in the other it is going to default to the local getTimezoneOffset() if not specified. So trying to figure out how to take that range and work with that. To do everything accordingly.
Ideas? Am I even approaching this in a correct manor?
The timestamps I am working with are already UTC, not sure of that makes a difference.
The JavaScript Date type has many problems, but one of its major quirks is that it only understands two time zones - UTC, or Local. It uses UTC internally and in certain properties and functions like .toUTCString(), but otherwise it uses the local time zone.
Many browsers will accept an offset when parsing a Date from a string, but that will just be used to set the UTC time. Anything on the way out will be converted back to the local time zone again.
Fortunately, there are some great libraries out there for working around these problems. Moment.js is perfectly suited for this. Here is an example of what you might be looking for:
moment(1373439600000).zone(8).format("YYYY-MM-DD HH:mm:ss Z")
// output: "2013-07-09 23:00:00 -08:00"
Of course, you can format as needed, or pass in a more complex zone offset like "+05:30". And if you need to use an actual IANA time zone, there is the moment-timezone companion project, which you could do something like this:
moment(1373439600000).tz('America/New_York').format("YYYY-MM-DD HH:mm:ss Z")
// output: "2013-07-10 03:00:00 -04:00"
Unfortunately the Date object does not provide may facilities for working with timezones. If you have the offset though, you should be able to compute the offset in milliseconds. Then you can add (subtract?) that value to your timestamp and use it to construct the appropriate Date.
Does that help?

Categories

Resources