Show date with format - javascript

I have:
var date = new Date();
and i have many formats:
var one = 'yy-mm-dd';
var two = 'dd.mm.yy';
var three = 'dd/mm/yy';
var four = 'mm/dd/yy';
Is possible to showing current date with this four formats? I know - i can use clause IF or SWITCH and set this, but maybe in JavaScript or jQuery without external libraries i can use this format as option?

If you're also already using jQuery UI, there's a string formatter function in the DatePicker.
If not, use Datejs.

You will have to do it yourself by using getFullYear(), getMonth() and getDate() and combining them as you see fit (no jquery/jquery UI required).
If you are using or can use JQuery UI you can take advantage of the $.datepicker.formatDate method (that's the approach we took).
Your question has been asked (in a somehow different form) before

Related

Is the IF function removing the date object in javascript?

I've spent an hour looking for answers and trying different things so I appreciate any help here.
The following code works great for finding someone's part B effective date. However, when someone's birthday is really on the 1st of a month the 'if' function get's used, and I'm no longer able to format and write the date. It's almost like 'partB_eff' is no longer a date object. (I'm a newbie, so I might just be making this part up.)
I'm getting the error "TypeError: partB_eff.toLocaleDateString is not a function at AutoFill_6_Step_Checklist(Code:24:27)"
How can I resolve this?
let birthday = new Date(e.values[2]);
//this is a date entered from a google form
let bdayCopy = new Date(birthday);
//I created this since I'll be using .setMonth(), and I don't want to change the original date of the birhtday
let bday65 = new Date(bdayCopy.setMonth(bdayCopy.getMonth()+780));
//finds the 65th birthday
let partB_eff = new Date(bdayCopy.setDate(01));
//find's the Medicare part B effective date (the 1st of the month someone turns 65)
if(birthday.getDate()==1){
partB_eff = partB_eff.getMonth-1;
//if the person's birthday is really on the 1st of the month, the part b effective date is the 1st of the month prior. partB_eff must be converted
}
partB_eff = partB_eff.toLocaleDateString('en-us',{year:"numeric",month: "short",day:"numeric"});
//format partB_eff so that it looks nice on paper
partB_eff = partB_eff.getMonth-1;
Doesn't do what you think it does. What it does is get the vound function getDate from your date object, and attempt to subtract one from it. In any other language trying to do subtraction on a function would be a type error, but Javascript is Javascript and allows numeric operations on almost any type. A function minus a number in JS is NaN. NaN doesn't have a method called toLocaleString, hence the error.
What's interesting is that you did the same operation correctly above with bdayCopy.setMonth(bdayCopy.getMonth()+780)
Just do the same thing here
bdayCopy = new Date(bdayCopy.setMonth(bdayCopy.getMonth()-1));
Also some important concepts. if in Javascript is not a function. if is a keyword that starts a conditional statement. You can't do any of the things you can do with a function with if. You can't call it or assign it to a variable or pass ot as a function argument. Clearly understanding what a function is is something you need to do to be able to work in JS, or frankly any other language.
Finally if you are doing date math in JS I strongly recommend you use a date library like DateFns or Moment. Javascript native date APIs are possibly the worst designed date API of any language ever.

Changing date format from dd/mm/yyyy to yyyy-mm-dd in knockout.js

I have no experience of using knockout.js. I've inherited a booking form which uses a mixture of knockout and C# ASP.NET. We recently upgraded the database to the latest version of MySQL, which is a lot more particular about the format in which the date is entered than the older version. In most cases I've been able to get around this by tweaking either C# or SQL, but in one part of the form I haven't found a solution. The dates are prepopulated in the form input in dd/mm/yyyy format. I want to change this to yyyy-mm-dd so that I can use date inputs rather than text inputs
There are two form inputs which look like this
<input type="text" size="10" maxlength="10" class="normaltext" data-bind="attr:{id:'returnDate-'+Id},value:FlightInfo.ReturnDate, enable:$root.FlightsAdvanced() == 'true' && !FlightInfo.OwnFlight()">
The other one, obviously, is for the departure date. They appear to be populated from the following function in a javascript file.
function FlightInfo(depDate, retDate) {
this.OwnFlight = ko.observable(false);
this.FirstCode = ko.observable("");
this.SecondCode = ko.observable("");
this.DepartureDate = ko.observable(depDate);
this.ReturnDate = ko.observable(retDate);
this.ReqTransferIn = ko.observable(0);
this.ReqTransferOut = ko.observable(0);
}
If I replace ko.observable(retDate) with a hard coded date, eg 2020-09-09, and submit the form then it works, however if I hard code the same date directly into the text input in place of value:FlightInfo.ReturnDate then it doesn't - the form takes the date in the wrong format from knockout and an error is thrown.
I've tried using moment.js as suggested in this question, but it didn't work for me. How can I reformat depDate and retDate as yyyy-mm-dd
I eventually solved this in the C# layer by changing a few instances of .ToShortDateString() to .ToString("yyyy-MM-dd").
Using moment.js is the right way to achieve this, when creating flightInfo, two observables should be modified like this:
this.DepartureDate = ko.observable(moment(depDate).format('YYYY-MM-DD'));
this.ReturnDate = ko.observable(moment(retDate).format('YYYY-MM-DD'));
if these changes do not reflect in your text input, than you should debug if you have moment.js included and activated in proper manner.

Angular2+ How to display milliseconds from date?

I was using a custom pipe for displaying time, and now I tried to change it so that I could also display milliseconds:
{{log.LogDate|jsonDate|date:'dd.MM.yyyy HH:mm:ss.sss'}}
The pipe itself:
if (typeof (value) === 'string') {
if (value.includes('/Date('))
return new Date(parseInt(value.substr(6)));
}
return value;
However, milliseconds have the value of seconds:
log.LogDate: 2017-05-08T15:45:38.2527293+
02:00
Output from pipe: 08.05.2017 15:45:38.38
Full jsonDate pipe(no format): 2017-05-08T15:45:38.2527293+02:00
I am new to Javascript, and I am not sure if this is an Javascript or an Angular issue, however, I would like it to work inside Angular.
Is it possible to do this using pipes, or is there another/better way to do this?
Since angular 5 you can use SSS to add milliseconds to your date.
See https://angular.io/api/common/DatePipe
So your example would look like
{{log.LogDate|jsonDate|date:'dd.MM.yyyy HH:mm:ss.SSS'}}
Changelog for angular 5:
- [...]
- fractional seconds are now supported with the format S to SSS.
- [...]
It's an Angular issue. AngularJS supports milliseconds, but Angular (2+) does not (GH issue).
You can very well drop the date pipe and use only your custom one for this task. Your example however doesn't seem to handle dates very well. Without going into details I suggest you use some external library to do the formatting
for you inside your pipe. Otherwise it would be a lot of effort for little reward. My personal weapon of choice is Moment.js
After importing it correctly you would simply use:
moment(value).format('DD.MM.YYYY HH:mm:ss.SSS');
If you want a dirty way out of this without importing external libraries, you could use Angular date pipe as it is (with seconds only) and then pipe it to add milliseconds on your own.
Another possibility is to stay with angulars pipe and extract the milliseconds via javascript-method:
{{ Datetime | date:'dd.MM.yyyy HH:mm:ss' }}.{{ getMillies(Datetime) }}
----
public getMillies(input: Date): number
{
return new Date(input).getMilliseconds();
}
With Angular 5, a new Date-Pipe is in progress, to support M

how to find hh:mm:dd difference between two strings in Javascript

In my app I have two date strings:
Say that they are:
date1 = "2014-03-14 18:25:15";
date2 = "2014-03-14 16:26:15";
I get these date strings based on two events that the customer selects. Now I need to show the difference between these two strings in HH:MM:DD format.
What I am currently doing is, posting to PHP using AJAX and then doing the calcuation in the server:
$rDate = new DateTime($date1);
$tDate = new DateTime($date2);
$interval = date_diff($rDate,$tDate);
echo $interval->format('%h:%i:%s');
Then in the AJAX response handler I print it to a div
My problem is that server trip is just too much an overkill for this. How can I achieve the same thing from browser itself? (Javascript/Jquery/MomentJS)...
Any help is greatly appreciated!
I'd suggest looking into Moment.js, which is a very well featured date handling library for Javascript.
Here's the relevant manual link for Moment.js for what you're wanting to do: http://momentjs.com/docs/#/displaying/difference/
Hope that helps.

Detect the ID of the current user timezone using moment.js

What I'm looking for is a way to detect the browser's timezone ID (as defined in the Olson tables) but I don't care for the exact ID, I just need the ID of a timezone that works the same as the user's one (for example "Europe/Rome" is fine if the user is in Paris).
I'm not interested in the current offset, I really need the timezone so that I can send it to the server to do computations for other dates (the server has the Olson tables too).
Theoretically, as I already use Moment.js timezone library and have included the Olson tables, I don't need anything else, but I don't find any API to do the detection. I don't know if it's hidden somewhere or if somebody has it already written. One of the problems is that the current timezone plugin seems to keep its data private.
I dont' want a solution based on the integration of yet another copy or extract of the Olson tables (which I would have to maintain), I know there are a few libraries duplicating them, I want to use the ones I already have in Moment.js.
I made a small script to do that detection. It starts by registering the ids of the available timezones, then, on a call to the matches function tests all timezone ids for the current time and the times 4 and 8 months later (to filter out the timezones with different daylight rules) and five years before.
Here it is :
<script src="moment-with-langs.min.js"></script>
<script src="moment-timezone.min.js"></script>
<script src="moment-timezone-data.js"></script>
<script>
var tzdetect = {
names: moment.tz.names(),
matches: function(base){
var results = [], now = Date.now(), makekey = function(id){
return [0, 4, 8, -5*12, 4-5*12, 8-5*12, 4-2*12, 8-2*12].map(function(months){
var m = moment(now + months*30*24*60*60*1000);
if (id) m.tz(id);
return m.format("DDHHmm");
}).join(' ');
}, lockey = makekey(base);
tzdetect.names.forEach(function(id){
if (makekey(id)===lockey) results.push(id);
});
return results;
}
};
</script>
If you just want one timezone id, simply use
var tzid = tzdetect.matches()[0];
Demonstration
GitHub Repository : https://github.com/Canop/tzdetect.js
Update : The code here shown isn't compatible with the most recent versions of moment.js. Please refer to the GitHub repository for a maintained (free to use) code.
2017 Update: There's now an API in moment.js to guess the timezone. That's probably the best solution right now.
If you want to use the standard JavaScript API, you can use Intl.DateTimeFormat.resolvedOptions where there is browser support:
Intl.DateTimeFormat().resolvedOptions().timeZone; // "America/Los_Angeles"
resolvedOptions is currently (Jan 2016) available in all browsers except Safari on iOS and desktop: http://caniuse.com/#feat=internationalization
However, the timeZone property is currently only available on Chrome.
moment now has the guess() API as described here
There's a javascript tool that does just that :
https://github.com/entraigas/jstz
It seems to deal with timezones ambiguity also.
Combined with momentJS timezone, you can get the timezone and show formatted date :
var tzObj = jstz.determine();
var timezoneCode = tzObj.name();
console.log(moment.tz(timeZoneCode).format());

Categories

Resources