Adding days to input date with strange console log results - javascript

I'm trying to return a date in format i.e(12-5-2013) to the variable 'returningOn' by adding 'stayingFor' days number to the formatted 'dateObj' in the same format.
But i seem to be getting bizarre values when i do some console.logs. Why is this? Also, What date format is the last variable in?
var leavingOn = $('#leavingOn') != 'undefined' ? $('#leavingOn').val() : '12-7-2013';
var stayingFor = $('#stayingFor') != 'undefined' ? $('#stayingFor').val() : 7 ;
var splitDate = leavingOn.split('-');
var dateObj = new Date(Number(splitDate[0]), Number(splitDate[1]) -1, Number(splitDate[2]));
var returningOn = dateObj.setDate(dateObj.getDate() + stayingFor);
console.log(splitDate); // ["2013", "11", "14"]
console.log(leavingOn); // 2013-11-14
console.log(stayingFor); // 7
console.log(dateObj); // Fri Jul 25 2014 22:00:07 GMT+0100 (GMT Daylight Time)
console.log(returningOn); // 1406322007249

I think the stayingFor variable needs to be converted to an integer. Try:
stayingFor = parseInt(stayingFor);

Related

Format/parse different Date formats correctly

I receive Date in 3 formats from different APIs
UTC format: 2014-01-01T00:00:00.000Z (String)
GMTformat: Thu, 29 Nov 2018 17:30:56 GMT (String)
unixTimeStamp: 1558606726 (number)
Also the UTC format sometimes might not have Z in the end so the normal parsing will give a time difference.
function formatDate(dateString) {
var dateTime, utcFormatRegex, zeroHourOffsetRegex;
// Some APIs return a Date in standard ISO UTC format may not have Z at the end
utcFormatRegex = /^\d{4}-\d{2}-\d{2}T.*$/;
zeroHourOffsetRegex = /^.*Z$/;
if (utcFormatRegex.test(dateString) && !zeroHourOffsetRegex.test(dateString)) {
dateString+='Z';
}
dateTime = new Date(dateString);
}
Given that there are parsing functions for all of the different formats, i need a function that determines which parsing function we should be using based on a regex and parse it accordingly. If regex is not the ideal solution then how can i approach this?
What I'm getting at is there should probably be a more robust solution than 'if there isn't a Z then add one' to get it to parse through the single date time parser. What if we get another date time format that doesn't play nicely with a Z on the end? We'll be making multiple changes at that point in time.
Using a regular expression is OK, but you need to test strictly for the formats you're expecting. If you get something you don't expect, throw an error. It's one of the failings of current built–in parsers is that there's no way to specify strict parsing, e.g. where a format is supplied and the parser throws an error if the input string doesn't match.
There are libraries that can help, a search will reveal quite a few.
But if you only have to support the 3 formats in the OP, something like the following may suit:
/* Return a Date where the input may be:
** string: ISO 8601 timestamp that should be treated as UTC
** whether it has a trailing Z or not
** string: Timestamp in the format (using moment.js tokens):
** ddd, DD MMM YYYY HH:mm:ss GMT
** nunber: UNIX time value, seconds since 1970-01-01 UTC
*/
function toDate(value) {
// Parse the string & fail early if it fails
let d = new Date(value);
// Throw error if couldn't parse value
if (isNaN(d.getTime())) {
throw 'Invalid timestamp: ' + value;
}
// Otherwise, do the work
let days = 'Sun Mon Tue Wed Thu Fri Sat'.split(' ');
let months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
// Test for time value first as that's the easiest
if (typeof value == 'number' && !isNaN(value)) {
return new Date(value * 1000);
// Test for ISO 8601 next
} else if (/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\dZ?$/.test(value)) {
return new Date(/Z$/.test(value)? value : value + 'Z');
// Test for random format
} else if (/^[a-z]{3}, \d?\d [a-z]{3} \d{4} \d\d:\d\d:\d\d GMT$/i.test(value)) {
let b = value.split(/ |:/);
if (days.includes(b[0].substr(0,3)) && months.includes(b[2])) {
let x = new Date(Date.UTC(
b[3], // year
months.indexOf(b[2]), // month, zero indexed
b[1], // day
b[4], b[5], b[6] // hh:mm:ss
));
// Check value was a valid date, only need to check some parts
if (x.getUTCFullYear() == b[3] &&
x.getUTCDate() == b[1] &&
x.getUTCHours() == b[4] &&
x.getUTCSeconds() == b[6]) {
return x;
} else {
throw 'Invalid timestamp: ' + value;
}
}
// Throw error as must be unknown format
} else {
throw 'Unknown format: ' + value;
}
}
// Minimal testing
var isoString0 = '2014-01-01T00:00:00.000Z',
isoString1 = '2014-01-01T00:00:00.000', // no Z, parse as UTC anyway
randomString = 'Thu, 29 Nov 2018 17:30:56 GMT',
unixTimeValue = 1558606726, // Assume seconds
invalidDate0 = '2018-02-29T00:00:00.000Z', // no 29 Feb in 2018, fail built-in parse
invalidDate1 = 'Thu, 29 Feb 2018 17:30:56 GMT', // no 29 Feb in 2018, fail manual parse
invalidFormat = '6/6/2019'; // Unknown format
[isoString0, isoString1, randomString, unixTimeValue, invalidDate0,
invalidDate1, invalidFormat].forEach(s => {
var result;
try {
result = toDate(s);
console.log(s + ' =>\n' + result.toISOString());
} catch (e) {
console.log(e);
}
});

datetime convert to date string - javascript

I have following datetime value in a json :
Fri Jan 22 2016 14:34:38 GMT-0500
I would like to display something like "January 22, 2016"
How could I achieve this in javascript. I have JQuery, Extjs libraries available.
Try creating object having properties of abbreviated months, values of full month, using for..in loop , String.prototype.slice(), String.prototype.replace()
var months = {
"Jan":"January",
"Feb":"February",
"Mar":"March",
"Apr":"April",
"May":"May",
"Jun":"June",
"Jul":"July",
"Aug":"August",
"Sep":"September",
"Oct":"October",
"Nov":"November",
"Dec":"December"
};
var date = "Fri Jan 22 2016 14:34:38 GMT-0500";
// extract "Jan 22 2016" from `date`
var d = date.slice(4, -18);
for (var prop in months) {
if (new RegExp(prop).test(d)) {
// replace abbreviated month with full month name
d = d.replace(prop, months[prop]);
// replace day with day followed by comma `,` character
d = d.replace(/(\d{2})(?=\s)/, "$1,")
}
}
document.body.textContent = d
This question is addressed to the same question of yours. You can use the functions shown here to construct the date string as you want.
// This could be any Date String
var str = "Fri Feb 08 2013 09:47:57 GMT +0530 (IST)";
var date = new Date(str);
This will then give you access to all the Date functions (MDN)
For example:
var day = date.getDate(); //Date of the month: 2 in our example
var month = date.getMonth(); //Month of the Year: 0-based index, so 1 in our example
var year = date.getFullYear() //Year: 2013
Extract date and time from string using Javascript
Found this crazy method here, but worked!
Converting milliseconds to a date (jQuery/JS)
Here is the fiddle that i'v done
https://jsfiddle.net/Ripper1992/hj6L2Lvz/
var now = new Date("Fri Jan 22 2016 14:34:38 GMT-0500");
alert(now.customFormat( "#MMMM# #DD#, #YYYY#" ) );
customFormat is the function called to get each part of the Data, parse and replace based on the #MMMM# or #DD# or #SS# defined by the user.
And here is the complete function with the documentation
http://phrogz.net/JS/FormatDateTime_JS.txt

Convert JavaScript new Date() to php DateTime()

I have 2 fields in HTML:
<input id="datum" type="date">
<input id="uhrzeit" type="time">
JavaScript:
var datumUhrzeit = new Date($("#datum").val()+","+$("#uhrzeit").val());
console.log(datumuhrzeit);
"Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)"
How can I convert "Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)" in PHP to a DateTime, so that I can save it to postgresql?
You can get unix timestamp from Date object as follows (see Date.prototype.getTime)
var timestamp = '#' + Math.round(datumUhrzeit.getTime()/1000);
Then when sent on server simply create new datetime object
$datumUhrzeit = new DateTime($timestamp);
If you can't use javascript to create timestamp and you get the the data from form directly you can do something like this, remember to set the timezone:
$datum = $_GET['datum'];
$uhrzeit = $_GET['uhrzeit'];
$datumUhrzeit = DateTime::createFromFormat('Y-m-d H:i:s', $datum . ' ' . $uhrzeit, new DateTimeZone('Europe/Berlin'));
Now as you have saved your date to the database and retrieved it, you can send it back
print $datumUhrzeit->format('U'); // This will print the time as unix timestamp
After that you would create your javascript date object with just the timestamp
var datumUhrzeit = new Date(timestamp * 1000); // timestamp from above
If you for some reason don't want to use unix timestamp you can print it in desired format with format method. Remember to set the timezone beforehand
$datumUhrzeit->setTimezone(new DateTimeZone('Europe/Berlin'));
print $datumUhrzeit->format('Y-m-d H:i:s');
Because javascript doesn't work well with timezones I would advocate you to use unix timestamps when you can. This way you have less problems with timezones.
You can use this javascript function to convert the dateObject or date string to your desired format:
/**
* Formats a dateObject or date string to Y-m-d date
* Example: Converts dateObject or date string Sat Aug 19 2017 00:00:00 GMT+0530 (India Standard Time) TO 2017-08-19
*/
function format_date( date )
{
if (typeof date == "string")
{
date = new Date(date);
}
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year+'-'+month+'-'+day;
}
var dateString = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
var formattedDate = format_date(dateString);//returned formatted date is 2015-08-18
Then you can pass this formatted date to your PHP code where you can use function strtotime to convert this date to your desired format. For ex:
$myFormattedDate = date('d-m-Y', strtotime($_REQUEST['formattedDate']));
You can do something like
$datumUhrzeit = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
$datumUhrzeit = substr($datumUhrzeit, 0, strpos($datumUhrzeit, '('));
$resultDate = date('Y-m-d h:i:s', strtotime($datumUhrzeit));
echo $resultDate;
try this one
function myFunction() {
var content = document.getElementById("datum").value+","+document.getElementById("uhrzeit").value;
console.log(content);
}

javascript date conversion showing wrong month

In the following date conversion after converting back the long integer The date says october instead of september
var date = 2013-09-23 18:31
startdate = getTimeStamp(date); //1382533260000
Now
t=1382533260000
rt = new Date(t)
//Wed Oct 23 2013 18:31:00 GMT+0530 (India Standard Time)
function getTimeStamp(strDate) {
var a1=strDate.split(" ");
var d1=a1[0].split("-");
var t1=a1[1].split(":");
var dtObj = new Date(d1[0],d1[1],d1[2],t1[0],t1[1]);
return dtObj.getTime();
}
In JavaScript, month numbers are numbered 0-11.
If you're parsing from components like this into the Date constructor you'll have to subtract one from the number:
function getTimeStamp(strDate) {
var a1=strDate.split(" ");
var d1=a1[0].split("-");
var t1=a1[1].split(":");
var dtObj = new Date(d1[0],d1[1] - 1,d1[2],t1[0],t1[1]);
return dtObj.getTime();
}
Months are zero-based, so January is zero, February is one, etc..
So you need to use d1[1]-1 in your new Date() constructor.
Javascript month parameter starts from 0 upto 11 so, passing 8 means september

wrong date created with Javascript

I have a problem that seems so senseless that I'm sure I'm missing something really stupid.
I have the following Javascript function that validates a date:
function validateDate(date){
var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
if(!re.test(date))
return false;
var separator = (date.indexOf("/") != -1) ? "/" : "-";
var aux = date.split(separator);
var day = parseInt(aux[0]);
var month = parseInt(aux[1]);
var year = parseInt(aux[2]);
alert(aux[0]+" "+aux[1]+" "+aux[2]);
var dateTest = new Date(year,month-1,day);
alert(dateTest); //2nd alert
if(dateTest.getDate() != day)
return false;
if(dateTest.getMonth()+1!= month)
return false;
if(dateTest.getFullYear() != year)
return false;
return true;
}
the first alert always shows the correct values.
if the incoming date is for example 05/07/2011, everything works fine. The second alert shows "Tue Jul 5 00:00:00 UTC+0200 2011" which is right.
but now, if i change the date month to august or september, the created date is wrong. for example, with date 05/08/2011, the second alert will show "Sun Dec 5 00:00:00 UTC+0100 2010".
anyone knows what could be happening??
Make sure you supply a radix to parseInt. If you don't, it will "guess" based on the string. In this case, your 08 is being parsed as an octal value because of the prefixed zero and you get 0 back.
var day = parseInt(aux[0], 10);
var month = parseInt(aux[1], 10);
var year = parseInt(aux[2], 10);
Supplying a base ten number will get you the correct result.
//Parsing numbers:
parseInt("06"); // 6, valid octal
parseInt("07"); // 7, valid octal
parseInt("08"); // 0, invalid octal
parseInt("09"); // 0, invalid octal
parseInt("10"); // 10, parsed as decimal
parseInt("11"); // 11, parsed as decimal
parseInt("12"); // 12, parsed as decimal

Categories

Resources