I'm kinda new to Javascript.
My problem is the following : I have to implement a form that is generated by a js file, by taking the url and paste it inside my HTML. I have a date input, and I need to verify if the date is right, wether it is dd/mm/aaaa or mm/dd/aaaa.
If possible, without using regExp. I already made this function out of StackOverflow RegExp :
function validateDateRegExp(field){
var date=field.value;
var regExp1 = /^(((0[1-9]|[12]\d|3[01])[\s\.\-\/](0[13578]|1[02])[\s\.\-\/]((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)[\s\.\-\/](0[13456789]|1[012])[\s\.\-\/]((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])[\s\.\-\/]02[\s\.\-\/]((19|[2-9]\d)\d{2}))|(29[\s\.\-\/]02[\s\.\-\/]((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var regExp2 = /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$/;
if(!(regExp1.test(date)||regExp2.test(date))){
alert(date);
document.getElementById('fld_CS_BuyingDate').value="";
}
}
I'm looking for a solution since 2 days, but the answers are not clear, or the problem is not the same.
Does anyone have any idea on how I could work that out ?
Thanks for the future answers
Related
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();
}
I need some help with validating a date time string in Javascript, based on the browser's language.
I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be
dd/MM/yyyy HH:mm:ss
I tried using something like this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);
However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.
Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.
I have tried using the following webmethod, which works with en-US but nothing else:
Public Function ValidateDates(ByVal strDate_In As String) As String
Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
Try
Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
Return "true"
Catch ex As Exception
Return "false"
End Try
End Function
You can use Regex to do this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);
Demo: https://jsfiddle.net/kzzn6ac5/
update
The following regex may help you and improve it according to your need:
^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$
It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss
Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1
Further Regex expressions relevant to date matching can be found here.
JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.
But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:
try {
var user_input = $("#theDate").val();
var split = user_input.split(" "); // 0: date, 1: time
var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds
d.setHours(split_time[0]);
d.setMinutes(split_time[1]);
} catch {
// not in a valid format
}
This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Formatting a date in javascript
I am new to Javascript / JQuery...and right now all I am trying to do (to learn) is to make a page that extracts information from a google calendar (public) and displays the events along with start date + time plus end date and time. So far I have:
<script type="text/javascript">
$(document).ready(function () {
var baseURL = "https://www.googleapis.com/calendar/v3/calendars/qq3hkhn3dj8gt05q539smmk2go#group.calendar.google.com/events?key=AIzaSyB66zMow3CSeTdM1m_X_0Wj1JxCtSTd8kU&alt=json&callback=?";
$.ajax({
url: baseURL,
dataType: 'json',
success: function(result) {
console.log(result.items[0].created);
}
});
});
</script>
In my console, the output I see is:
2012-01-07T23:46:15.000Z
Now, what I want to do is, parse this date and time into a pretty looking string, something like "January 1, 2012" and same for the time. How should I proceed? I do not want to step outside JS / JQuery / AJAX.
Also, I would appreciate comments / feedback on my code so far - does this seem a normal / good way to do it, or should I approach it differently?
Thanks, let me know please!
You could try something like this:
var date = new Date(result.items[0].created);
date.toLocaleString();
The format of toLocaleString() is different by browser. If you want precise control over the format, try using a library such as Datejs, XDate, or the formatDate function provided by jQuery UI.
You need to parse date string and convert it to date. This date library in Javascript contains some useful functions for the conversion you need.
http://www.mattkruse.com/javascript/date/source.html
I think you can use getDateFromFormat function in this.
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''));
var formattedDate = new Date(parseInt(dateNum.substr(6)));
alert(formattedDate);
What's wrong with this code? Why does it not execute and give me the desired result...
Try this.
var formattedDate = new Date(parseInt(dateNum.toString().substr(6)));
Felix's comment is the answer :)
I've no idea why you're doing it in a complicated way - / / is for regular expressions, not for dates. Then you also have this notation inside a string. I'm not aware of any /Date(...)/ format. What you're doing on the first line is parsing the number out of it, but why not do it yourself?
This works fine:
var formattedDate = new Date(1306348200000);
alert(formattedDate);
To format it, you would need certain functions to combine the date components as described here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#Methods_2
Interesting function you have here. I see at least one problem dateNum is not a string.
Might be a good idea to submit what you expect to get from your code.