Need help on displaying readable date using javascript - javascript

I'm new to javascript and I've got this problem of showing dates.
I would like to display a readable date formatted like MM-DD-YYYY, but everytime I try to load the page, I always get an ASP format date.
Someone gave this code and I tried to use it on my project, yet, I still get the wrong format of date with this kind of error Uncaught TypeError: Cannot call method 'formatDate' of undefined.
What's wrong with this code?
$(document).ready(function () {
var date = $.datepicker.formatDate('yy-mm-dd', new Date($("#dateOfBirth").val()));
$("#dateOfBirth").val(date);
});
I'm using C# MVC.

Might give this a try (assuming you're using jQuery... If I'm way off, I apologize):
// You might not need the next two lines...
// And if not, just delete them as well as the last line
jQuery.noConflict();
jQuery(function($) {
$(document).ready(function() {
$("#dateOfBirth").datepicker();
$("#dateOfBirth").datepicker("dateFormat", "yy-mm-dd");
});
});

Related

How to convert UTC time to local time in Javascript

My backend is in Django. I used Django's auto_now_add feature on the model to add the current time when that model was created. For example, I am passing this value to the function: 2019-10-08 09:16:20.666754+00:00.
How to convert this in local time in Javascript? I have not coded JS. So the line's a bit blurry for me.
I tried the following method:
function localize_time(date) {
date = new Date(date);
date = date.toString();
}
Then I saw another SO post to add "UTC", that's not working either. when I am calling a said function from Django's template, it's showing following error:
Uncaught SyntaxError: missing ) after argument list
It's on that function.
In Django's template, I am calling the function like this:
<script type="text/javascript">
localize_time({{ user.created_on | safe}});
</script>
If I don't add safe, then the error is:
Uncaught SyntaxError: Unexpected number
Thanks in advance.
I converted the Django's time in milliseconds using datetime.timestamp method and rest of things worked like magic.
you need to add UTC at the end of your date string.
const date = new Date('2019-10-08 09:16:20.666754+00:00 UTC');
alert(date.toString())

show certain date in date picker

I'm using pickmeup datePicker in my Angular project, and it works good and stable but I faced a problem. When I'm trying to set a particular date, picker breaks and/or disappears. I used the method set_date from the documentation but I think I'm missing something.
I use the following code
showDate(timestamp: number) {
const timeString = timestamp.toString();
this.pickerInstance.set_date(new Date(timeString));
}
I have a stackblitz code template here.
So the idea is, I want to have a button when I'm pressing on it, it passes timestamp value to showDate function and after that datePicker shows my date.
I don't want to use jquery here, I believe this could be done without it. But maybe I'm wrong.
Any ideas, comments, help is welcome? thank you.
The constructor of Date needs a number not a a string.
You need to call this.pickerInstance.update() after the update
public showDate(timestamp: number) {
this.pickerInstance.set_date(new Date(timestamp));
this.pickerInstance.update();
}

IE11 Dates from a text field in a variable not passing properly to a service

So I have a website that uses dates to search a database. When working in Firefox and Chrome everything works just fine, but when I toss it into IE (specifically IE 11) the searching wont work. I've narrowed down my issue to when I get the data from a text field using jquery it wont pass correctly.
Here is an example:
var start= $('#startdate').val();
var end = $('#enddate').val();
$.post(this.url(), {start: start, end: end }, function(data) {
// do stuff with data
}));
Now what I have tried is messing around in the console and in the js file itself. The following things work fine:
new Date('12/1/2016'));
new Date(Date.parse('12/1/2016')));
var start = '12/16/2016';
new Date(start ));
new Date(Date.parse(start)));
But as soon as I add a jquery selector into the mix it breaks and no longer works. Has anyone encountered this before?
So I know I'm late, but I was able to figure this out. Apparently in IE just setting the value of the underlying text field wont actually update the value in the datepicker, you have to set the value yourself.
For example:
$('#startdate').datepicker('setDate', start);

Calculate date difference in jQuery

The question is; there are 2 fields in my application, one is date (Field1) and second is a label (Field2). So, I want that when user selects a date in field 1, then field 2 should be automatically populated (current date - date from field 1).
Can anyone help on how to implement it.
I'm using jQuery to display date:
// This displays the date dialog when user clicks on Field1
$('#Field1').click(function () {
$('#Field1').simpleDatepicker();
});
// Tried following code but it didn't worked
$('#Field1').click(function () {
$('#Field1').simpleDatepicker({
onSelect: function () {
$('#Field2').value(calculateDays($('#Field1').toString))
}
});
});
function calculateDays(dateString) {
var today = new Date();
var inputDate = new Date(dateString);
var days = today - inputDate;
return days;
};
This may look like pathetic code to some folks but I'm just a beginner, so any suggestions/comments are welcome.
Also please tell me if this can be done using html only and no need to go to jQuery. It is my understanding that the calculating days (difference between dates) code will go in jQuery since this needs to be fired after selecting date ('onSelect' event). Please correct if wrong.
I'm assuming that you're trying to use Karl Seguin's jquery.simpleDatePicker (it came top when searching for "simpledatepicker" on Google).
As Jimbo remarks in the comments, it's hard to advise on an MVC approach here — you say you want to do this purely with HTML, but HTML alone can't dictate behaviour (I'd say that's extremely un-MVC). HTML5 forms do allow some limited behavioural control (validation etc), and they also offer <input type="date"/>, but none of these help your situation.
So for this answer I'm just going to fix the mistakes in your code:
The plugin is initialised with the simpleDatePicker jQuery method — you forgot to capitalise the 'P';
The plugin itself caters for the click event. You should initialise it directly without waiting for user input;
There was no onSelect initialisation option in the source code: I chose to use a change event listener on the input to capture this;
You use the jQuery method value — that's native DOM Javascript — you should be using val instead;
toString won't work on DOM elements or jQuery objects — again, use the val method;
The native Date object can't parse dates in arbitrary formats — nor would your code produce a number of days if it did (it would just produce the difference in milliseconds). For this kind of functionality you should use a good date library: I've opted for Moment.
Resulting code (as demonstrated here):
$('#Field1')
.simpleDatePicker()
.on('change', function passValue(){
$('#Field2').val(calculateDaysFromNow($('#Field1').val()))
});
function calculateDaysFromNow(dateString){
return moment.duration(moment(dateString,'MMM DD YYYY').diff()).days();
}
A bit of elaboration on how I've used moment:
First of all, we want to parse #Field1's formatted date for an actual quantifiable date object:
moment(dateString,'MMM DD YYYY')
Next, we want to differentiate that from now. Like Date, moment assumes now if we pass no argument:
moment(dateString,'MMM DD YYYY').diff()
We don't want this as a date, but as a duration, so we'll pass it to moment's duration method:
moment.duration(moment(dateString,'MMM DD YYYY').diff())
…and finally, we want this expressed in days:
moment.duration(moment(dateString,'MMM DD YYYY').diff()).days()
I'm not sure but this:
$('#Field2').value(calculateDays($('#Field1').toString)) should be like this:
$('#Field2').value(calculateDays($('#Field1').val())) or $('#Field2').value(calculateDays($('#Field1').text()))
Here is solution for setting same date in second field.
Link:jquery: using two datepicker with two fields ( field 1 , field2 + 1 day ) like booking.com
Change the format according to your need.

Removing the day from a date string with jQuery

I am trying to remove the "day" from every possible date occurrence on a page.
This is to make jQuery turn every date in the format of "08/22/2012" into "08/2012"
I was able to do this with this code: Replacing wildcard text using jquery
See my fiddle for more information: http://jsfiddle.net/CfZjF/223/
But it just isn't working within this table layout, regardless of what I have tried.
Another problem will be to specify the day specifically (maybe with wildcards?)-- that is the 2 numbers between the forward-slashes: /xx/, but please see the fiddle for more info.
Any ideas on how I can pull this off?
Try
str.replace(/\/\d+\//g, "/");
Or be more specific by replacing /(\d{2})\/\d{2}\/(\d{4})/g with "$1/$2" or something…
(Updated fiddle)
I think you should individually traverse the table cells instead of trying to globally muck with the entire rows HTML.
This assumes that your data is formatted as in your jsFiddle.
Updated fiddle: http://jsfiddle.net/GKrCS/
$('tr').each(function(){
$('td',this).not(':first').text(
function(){
return $(this).text().replace(/\/[0-9]+\//,'/');
});
});
Since all your dates are in the form xx/xx/xxxx, using a simple split() would always split it into an array with these values:
xx,xx,xxxx
So, something like this:
var totalDate = $("whateverYourDateSelectorMightBe");
var daysInMiddle = totalDate.val().ToString().split(",")[1];
so then you could do:
totalDate.val(totalDate.val().ToString().replace(daysInMiddle + "/",""));
Note that there are much cleaner ways to do this. I just did it this way because I think it better explains what I was trying to do.

Categories