DateTime-Locale value isn't being set by javascript - javascript

I have two DateTime-Locale input in a form, and I want to set the values of them to the date and time when the view loads, and 10 minutes after that. I've been following this to do it: Setting value of datetime-local from Date , but haven't been working.
These are examples of what I've been trying (in all the cases I've tried with document.getElementById("eve_start_date_id").value=... and var date = document.getElementById("eve_start_date_id"); date.value=...:
1º, I've tried this one, without the :ss and adding '.Replace(' ', 'T') to the ToString, but this doesn't even execute.
function defaultDate() {
var date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
document.getElementById("eve_start_date_id").value = date;
}
2º, this function completes, but the value doesn't get assigned. I've tried also with toLocaleDateString() and toISOString() to no avail:
function defaultDate() {
var d = new Date();
var elem = document.getElementById("eve_start_date_id");
elem.value = d.toLocaleString();
}
3º, this one also completes but neither assign the value. I've tried this changing the order of d.getDate()& d.getMonth(), changing the date join from /to -, the separator of date and time from to T, and adding :00 at the end of localDateTime, to no avail.
function defaultDate() {
Number.prototype.AddZero = function (b, c) {
var l = (String(b || 10).length - String(this).length) + 1;
return l > 0 ? new Array(l).join(c || '0') + this : this;
}//to add zero to less than 10,
var d = new Date(),
localDateTime = [d.getDate().AddZero(),
(d.getMonth() + 1).AddZero(),
d.getFullYear()].join('/') + ' ' +
[d.getHours().AddZero(),
d.getMinutes().AddZero()].join(':');
document.getElementById("eve_start_date_id").value = localDateTime;
}
At this point I don't know what I can try or if I missed some basic stuff to set the value. Any help is welcome

Okay, I've figured this out. I was using the format that the DateTime-Local gave when submitting the form (dd/MM/yyyy HH:mm) when the correct format to set the value is yyyy-MM-ddTHH:mm, so to make it work, the case 1 should look like this:
function defaultDate() {
var date = DateTime.Now.ToString("yyyy-MM-ddTHH:mm");
document.getElementById("eve_start_date_id").value = date;
}
And this is for the case 3, though it's easier using the case 1:
function defaultDate() {
Number.prototype.AddZero = function (b, c) {
var l = (String(b || 10).length - String(this).length) + 1;
return l > 0 ? new Array(l).join(c || '0') + this : this;
}//to add zero to less than 10,
var d = new Date(),
localDateTime = [d.getFullYear(),
(d.getMonth() + 1).AddZero(),
d.getDate().AddZero()].join('-') + 'T' +
[d.getHours().AddZero(),
d.getMinutes().AddZero()].join(':');
document.getElementById("eve_start_date_id").value = localDateTime;
}

Related

datetime not returning correct value

Using only JS Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.
I have wrote:
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var myDate = new Date(userDate);
var day = myDate.getDay();
var month = myDate.getMonth();
var year = myDate.getFullYear();
var d = day.toString();
var m = month.toString();
var y = year.toString();
return y + m + d;
}
console.log(formatDate("12/31/2014"));
but this is returning: 2014113
should it not return '20141231'
Thanks to #gurvinder372 by +1 I was able to get '20141231'
but the answer is telling me iv passed 0 out of 4...Ive failed on:
Example case: Wrong answer
Two-digit month and day: Wrong answer
One-digit day: Wrong answer
One-digit month: Wrong answer
Months in Date are counted from 0, so this:
myDate.getMonth();
will return 0 for January and so on.
Moreover this:
var day = myDate.getDay();
represents, the day of the week counted from 0, so it should be replaced with this:
var day = myDate.getDate();
For one-digit values, you need to check if it's less than 10 and conditionally prepend it with 0. So the final form of this should be:
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var myDate = new Date(userDate);
var day = myDate.getDate();
var month = myDate.getMonth() + 1;
var year = myDate.getFullYear();
var d = +day.toString() < 10 ? '0' + day.toString() : day.toString();
var m = +month.toString() < 10 ? '0' + month.toString() : month.toString();
var y = year.toString(); // no need for check one-digit values
return y + m + d;
}
Hope this helps you
function formatDate(userDate) {
var myDate = new Date(userDate);
var day = myDate.getDate();
var month = myDate.getMonth() + 1; // +1 as month starts with o
var year = myDate.getFullYear();
var d = (day <= 9) ? '0' + day : day.toString(); // append 0 for single digit
var m = (month <= 9) ? '0' + month : month.toString(); // append 0 for single digit
var y = year.toString();
return y + m + d;
}
console.log(formatDate("1/1/2014"));
You can even get rid of using Date constructor. Parsing with date constructor is usually not recommended unless you are using ISO-8601 format as implementation differs in browsers for other formats.
Here is an example with just string split() function.
If you want zero padding for single digit numbers, make use of the pad() function which formats 1 as 01.
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var dateArray = userDate.split('/');
var m = +dateArray[0];
var d = +dateArray[1];
var y = +dateArray[2];
var pad = function(n){return n >= 10? n : '0'+n};
// if you want zero padding
// return '' + pad(y) + pad(m) + pad(d);
return '' + y + m + d;
}
console.log(formatDate("12/31/2014"));
but this is returning: 2014113 should it not return '20141231'
Month starts from 0
Replace
var month = myDate.getMonth();
with
var month = myDate.getMonth() + 1;
If you also need to take care of single-digit padding, then do this as well
function padToTwoChar( value )
{
return ( "0" + value ).slice(-2);
}
and your return statement will become
return padToTwoChar( y ) + padToTwoChar( m ) + padToTwoChar( d );

How can I compare dates of format yyyyMMdd HHmmss.SSS in javascript while the inputs are of charecter format

How can I compare dates of format yyyyMMdd HHmmss.SSS in javascript while the inputs are of charecter format.I tried using date parse and other things.No luck
One way is to convert your dates to ISO-8601 format and load them using new Date() and compare the dates.
The other way is to use 3rd party libs like Moment js (momentjs.com/docs/).
var m1 = moment(dateStr1, 'YYYYMMDD HHmmss.SSS');
var m2 = moment(dateStr2, 'YYYYMMDD HHmmss.SSS');
if (m1 == m2) {}
Using plain JS
function toDate(d) {
var regex = /(\d{4})(\d{2})(\d{2})\s(\d{2})(\d{2})(\d{2})\.(\d{3})/;
var YEAR = 1, MONTH=2, DAY=3, HOUR=4, MIN=5, SEC=6;
var parts = date.match(regex);
return new Date(`${parts[YEAR]}-${parts[MONTH]}-${parts[DAY] ${parts[HOUR]}:${parts[MIN]}:${parts[SEC]}`);
}
var d1 = toDate('20170531 131515.765');
If by "compare dates" you mean if date1 is before date2 (i.e. < or > operators), the format you have will let you compare as strings:
var a = '20170531 231253.475';
var b = '20170531 231254.000';
console.log('a is before b? ' + (a.localeCompare(b) < 0));
console.log('b is before a? ' + (b.localeCompare(a) < 0));
If you want to compare them as Dates, you can parse the strings fairly easily:
var a = '20170531 231253.475';
var b = '20170531 231254.000';
// Parse date string in format yyyymmdd HHmmss.SSS
function parseSpecial(t) {
var y = t.substr(0,4);
var m = t.substr(4,2);
var d = t.substr(6,2);
var h = t.substr(9,2);
var M = t.substr(11,2);
var s = t.substr(13,2);
var S = t.substr(16,3);
return new Date(y, m-1, d, h, M, s, S);
}
console.log('a is: ' + parseSpecial(a).toString() +
'\nb is: ' + parseSpecial(b).toString());
console.log('Is a before b? ' + (parseSpecial(a) < parseSpecial(b)));
console.log('Is b before a? ' + (parseSpecial(b) < parseSpecial(a)));
Of course you should add validation to the parser to ensure you're comparing valid dates and provide default values for any missing parts.

how to format mysql timestamp into mm/dd/yyyy H:i:s in javascript

I am getting values from database which is a time stamp.And i need to convert it into mm/dd/yyyy H:i:s using javascript. i tried the following code. but its not working it firefox/ie.But its working in chrome..how to solve it.
function formatDate(value){
if(value){
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(value),
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
I am getting NaN/NaN/NaN/NaN/NaN/NaN in firefox and ie.Any help is much appreciated
Your code is missing a trailing }. If you formatted it better, you would see this:
function formatDate(value){
if(value){
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(value),
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
}
It works fine in Firefox, now.
Note that you are defining Number.prototype.padLeft each time you call this function. It would be better to move this out of the function body.
EDIT As per my comment, the reason this is failing for you is that the Date object will only accept strings in certain formats. Moreover, it occurs to me that your function is just changing the format of a string: You don't really need to bother messing about with dates and, instead, just do string operations on your input:
var formatDate = function(dateString) {
// Convert 'yyyy-mm-dd hh:mm:ss' to 'mm/dd/yyyy hh:mm:ss'
return dateString.replace(/^(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1');
};
Much easier!
function formatDate(d)
{
d = new Date(d * 1000);
return d.getMonth() + 1 + '/' + d.getDate() + '/' + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
Javascript already know how to work with a timestamp.
var d = new Date(timestamp * 1000); //will create a date object
You then can use all the Javascript Date methods to format it. (http://www.w3schools.com/jsref/jsref_obj_date.asp)
EDIT : Convert timestamp to milliseconds (*1000)

Date validation with JavaScript

I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012";​ // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
​
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}

jQuery javascript clock with settable time?

I am looking for a simple jQuery clock.
There are tonnes out there, but I am looking for one where I can set the current time, and the output format.
So I want to be able to call something like
$('#clock').clock({
format: 'l dS F Y, h:i a', //PHP date format, but anything that can mimic this output is good
date: '2012-07-01 23:59:59' //MYSQL date format, but can output as anything
});
Is there something like this (even raw js will do).
Creating a counter for a clock is pretty simple, you can probably write one in less time that it takes to review the answers you'll get here. Below is one I made as an example of prototype inheritance.
Just format the output however you like, add CSS to your hearts content to make it look good.
// Create a digital clock
// Write time in hh:mm:ss.nnn format
// el is an element
function Clock(el) {
if (typeof el == 'string') el = document.getElementById(el);
this.el = el;
}
// Clock methods
Clock.prototype = {
// Utilty functions
addZ: function(n) {
return n < 10? '0' + n : '' + n;
},
addZZ: function(n) {
return n < 10? '00' + n : n < 100? '0' + n : '' + n;
},
formatTime: function(d) {
return this.addZ(d.getHours()) +
':' + this.addZ(d.getMinutes()) +
':' + this.addZ(d.getSeconds()) +
// Milliseconds are just for debug, remove from finished version
'.' + this.addZZ(d.getMilliseconds())
},
update: function() {
var clock = this;
var d = new Date();
// Set next run to just after full second
var interval = 1020 - d.getMilliseconds()
this.el.innerHTML = this.formatTime(d);
setTimeout(function(){
clock.update();
}
,interval);
}
};
// Create a new clock
// el is id or element to display text in
function newClock(el) {
var y = new Clock(el);
y.update();
}
Edit
A generic date format function: http://blog.stevenlevithan.com/archives/date-time-format
A specific function to format a date to be like Tuesday 05th July 2011, 10:31 am:
var formatDate = (function() {
// Days of the week, zero is Sunday
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
// Months of the year, zero is January
var months = ['January','February','March','April',
'May','June','July','August','September',
'October','November','December'];
// Format single digit numbers
function addZ(n) {
return n<10? '0' + n : '' + n;
}
// Add ordinal to numbers
function addOrdinal(n) {
return ['th','st','nd','rd'][(''+n).slice(-1)] || 'th';
}
return function (date) {
var d = addZ(date.getDate());
var h = date.getHours();
var ap = h < 12? 'am' : 'pm';
h = addZ(h > 12? h - 12 : h);
return days[date.getDay()] + ' '
+ d + addOrdinal(d) + ' '
+ months[date.getMonth()] + ' '
+ date.getFullYear() + ', '
+ h + ':'
+ addZ(date.getMinutes()) + ' '
+ ap
}
}());

Categories