php Date Conversion to javaScript - javascript

Needs help in rewriting this php code in JavaScript
$date='20170721';
$stamps = strtotime($date);
$newdate = date('d M Y',$stamps);
$data = explode(' ', $newdate);
echo $data[0].' '.strtoupper($data[1]).' '.$data[2];
//output 2017 JUL 21
I am new in JavaScript this is what i have done so far
var date='20170721';
varstamps = strtotime($date);
var newdate = date('d M Y',$stamps);
var data = explode(' ', $newdate);
$data[0].' '.strtoupper($data[1]).' '.$data[2];

For better Result you can user https://momentjs.com/ Moment js
include moment js using
<script type="text/javascript" src="bower_components/moment/moment.js"></script>
var date = '20170721';
moment(date).format('YYYY MMM DD');

Here's a solution
var date = '20170721';
var year = date.slice(0,4),
month = date.slice(4,6),
day = date.slice(-2);
// create new Date obj
date = new Date(year, month, day);
// format using toLocaleDateString
console.log(new Date(year, month, day).toLocaleDateString('en-GB'));
// custom format
console.log(date.getFullYear() + ' ' + (date.getMonth()) + ' ' + date.getDate())
//output 2017 JUL 21

Php :
$date='20170721';
$stamps = strtotime($date);
Javascript :
var idate = 1500588000; // unix timestamp returned from php ($stamps variable)
var jdate = new Date(idate * 1000);
var day = jdate.getDate();
var month = jdate.getMonth();
var year = jdate.getYear();
var fulldate = jdate.toDateString();
Reference : Javascript Date - set just the date, ignoring time?

Currently i dont think javascript supports date conversions as this, but heres a work around
var str='20170721';
var datee=str.slice(0,4)+'-'+str.slice(4,6)+'-'+str.slice(6,8);
var date = new Date(datee);
var newDate = date.toString('yyyy MMMM dd');
console.log(newDate);
// Or you can decide to do this without any external library
var num =parseInt(str.slice(4,6));
var month='';
switch(num)
{
case 0:
month="January";
break;
case 1:
month="February";
break;
case 2:
month="March";
break;
case 3:
month="April";
break;
case 4:
month="May";
break;
case 5:
month="June";
break;
case 6:
month="July";
break;
case 7:
month="August";
break;
case 8:
month="September";
break;
case 9:
month="October";
break;
case 10:
month="November";
break;
case 11:
month="December";
break;
default:
month="Invalid month";
}
console.log(str.slice(0,4)+' '+month+' '+str.slice(4,6));
<script src="http://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>

Related

How to get the value from variable in switch statement is javascript

var day = "Sunday";
var x;
switch (day) {
case 0:
var x = 5;
day = "Sunday";
break;
case 1:
day = "Monday";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>
I want to get output as Today is Sunday 5
but I am getting the output as Today is Sunday undefined
How can get the value as 5 instead of undefined???
it is because of mistake in switch statement you are using number instead of day
like case 0: instead of case "sunday"
that is the mistake
var day = "Sunday";
var x;
switch (day) {
case "Sunday":
var x = 5;
day = "Sunday";
break;
case "Monday":
day = "Monday";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day + " " + x;
<p id="demo"></p>
you can try like this too with numbers
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
<p id="demo"></p>
<script>
var day;
var x=0;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day + x;
</script>
How can get the value as 5 instead of undefined???
variable in javascript will be initialized to undefined .so is out puts undefined because it didn't set to 5 in switch case (fails in condition to assing)
Answer is pretty simple:
switch (day) {
case 0:
var x = 5;
day = "Sunday";
break;
case 1:
day = "Monday";
break;
}
In the above code switch(day) you are passing a string "Sunday " and in cases matching it with an int type like case 0,it is not possible so try to pass an int in switch() or use case like case "Sunday":
switch (day) {
case "Sunday":
var x = 5;
day = "Sunday";
break;
case "anyday"://use case as you want
day = "anyday";
break;
}
You might find it easier to use an object to hold a set of keys/values. You can then check the object using the value held in day.
const days = {
sunday: 5,
monday: 2
};
let day = "Sunday";
const demo = document.getElementById('demo');
demo.innerHTML = "Today is " + day + " " + days[day.toLowerCase()];
<p id="demo"></p>

javascript passing a function that loops through array to a function that uses switch statement date method

I am trying to create a function that loops through an array and returns the results. I than am trying to pass this function to another function that uses a switch statement to check the dates of the values returned from the passed in function to display the day of the week ex sunday, wednesday etc to the console. All three values in the array are strings, with two of them being date values while the other is not.
I am obviously missing something as myDate function only returns one value, the first value from the array, also when it gets passed to the findDate function it does not return the expected results.
var myDate = function() {
var input = ['10/11/2009', '11/10/2010', '-1'];
for (var i = 0; i < input.length; i++) {
var result = input[i];
console.log(result);
return result;
}
};
console.log(myDate());
function findDay(myDate) {
if (myDate !== -1) {
var date = new Date(myDate), day = "";
switch (date.toDateString().slice(0,3)) { //Pick the first 3 characters of a date string
case "Sun":
day = "Sunday";
break;
case "Mon":
day = "Monday";
break;
case "Tue":
day = "Tuesday";
break;
case "Wed":
day = "Wednesday";
break;
case "Thu":
day = "Thursday";
break;
case "Fri":
day = "Friday";
break;
default:
day = "Saturday";
break;
}
console.log(day);
}
else{
console.log(myDate + ' is not a valid date'); //If input is -1
}
}
findDay(myDate);
Sample Input
10/11/2009
11/10/2010
-1
Sample Output
Sunday
Wednesday
-1 is not a valid date
If the myDate function is meant to apply some other function (findDay) to the list of inputs, it will need to look like this:
var myDate = function( callback) {
var input = ['10/11/2009', '11/10/2010', '-1'];
// loop through list and apply callback to EACH item
for (var i = 0; i < input.length; i++) {
callback(input[i]);
}
};
function findDay(dateString) {
if (dateString != -1) {
var date = new Date(dateString), day = "";
switch (date.toDateString().slice(0,3)) { //Pick the first 3 characters of a date string
case "Sun":
day = "Sunday";
break;
case "Mon":
day = "Monday";
break;
case "Tue":
day = "Tuesday";
break;
case "Wed":
day = "Wednesday";
break;
case "Thu":
day = "Thursday";
break;
case "Fri":
day = "Friday";
break;
default:
day = "Saturday";
break;
}
console.log(day);
}
else{
console.log(dateString + ' is not a valid date'); //If input is -1
}
}
myDate(findDay);
Then you just need to modify findDay slightly so that it works on each date string that you give it. Here is an example, if this is what you had in mind:
https://jsfiddle.net/2mnxcpwt/
Your logic is unclear. Usually you have a function which is a callback and some iterator for the array which calls the callback for every element. For example like this:
var input = ['10/11/2009', '11/10/2010', '-1'],
output = input.map(findDay); // iterator with callback
function findDay(myDate) { // callback
var date,
days = { Sun: 'Sunday', Mon: 'Monday', Tue: 'Tuesday', Wed: 'Wednesday', Thu: 'Thursday', Fri: 'Friday', Sat: 'Saturday' };
if (myDate !== '-1') { // <-- changed to string!
date = new Date(myDate);
return days[date.toDateString().slice(0, 3)];
}
return myDate + ' is not a valid date';
}
document.write('<pre>' + JSON.stringify(output, 0, 4) + '</pre>');
I think the main problem was, that you checked if if (myDate !== -1) { and set for myDate in the array the value to [..., '-1']. So you wanted to compare a string with a number.
Additional to the problem above I have packed the task in one function:
function findmyDate ( input ) {
input.forEach( function (myDate,k) {
if (myDate !== '-1') {
var date = new Date(myDate), day = "";
switch (date.toDateString().slice(0,3)) { //Pick the first 3 characters of a date string
case "Sun":
day = "Sunday";
break;
case "Mon":
day = "Monday";
break;
case "Tue":
day = "Tuesday";
break;
case "Wed":
day = "Wednesday";
break;
case "Thu":
day = "Thursday";
break;
case "Fri":
day = "Friday";
break;
default:
day = "Saturday";
break;
}
console.log(day);
}
else{
console.log(myDate + ' is not a valid date'); //If input is -1
}
});
};
findmyDate( ['10/11/2009', '11/10/2010', '-1'] );
Test the function at https://jsfiddle.net/nrp24x0w/
First, your array is:
['10/11/2009', '11/10/2010', '-1']
And, later you have:
if (myDate !== -1)
Which will never be true since the array contains a string and you are checking for a number.
Next, inside your loop, you have:
for (var i = 0; i < input.length; i++) {
var result = input[i];
console.log(result);
return result;
}
There are two issues here:
The return statement is in the loop, causing the loop to terminate
upon the first iteration.
Inside the loop, the old result value is being
thrown out and the result variable is being reinitialized with the latest loop iteration value.
You should have:
var myDate = function() {
var input = ['10/11/2009', '11/10/2010', '-1'];
var result;
for (var i = 0; i < input.length; i++) {
result += input[i];
}
console.log(result);
return result;
Now, you say "I am trying to create a function that loops through an array and returns the results." But, you haven't said how those results should be packaged. What do you want? A delimited list? Another array? Have you considered:
input.forEach(function(){ . . . });
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Or:
var resultArray = input.map(function(){ . . . });
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Since you seem to just want to check an array, it is not clear why you need a second array or a second function, but here's an example that does the main job:
function checkArray(arr){
arr.forEach(function(value, index, arr){
if (value !== -1) {
var d = new Date(value), day = "";
switch (d.toDateString().slice(0,3)) { //Pick the first 3 characters of a date string
case "Sun":
day = "Sunday";
break;
case "Mon":
day = "Monday";
break;
case "Tue":
day = "Tuesday";
break;
case "Wed":
day = "Wednesday";
break;
case "Thu":
day = "Thursday";
break;
case "Fri":
day = "Friday";
break;
default:
day = "Saturday";
break;
}
alert(day);
}
else{
alert(myDate + ' is not a valid date'); //If input is -1
}
});
}
var input = ['10/11/2009', '11/10/2010', -1];
checkArray(input);
Parsing of strings by the Date constructor is strongly recommended against as it is largely implementation dependent and unreliable. The format "10/11/2009" is ambiguous, for some it's 11 October, for most it's 10 November. I'll guess you mean 11 October since that's a Sunday.
So you should never use the Date constructor (or Date.parse, they are the same for parsing) to parse strings, a simple function to parse m/d/y format and validate the result is:
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d || new Date(NaN);
}
The result of date.toString() is entirely implementation dependent, there is nothing to ensure that the first three characters will be a day name so:
date.toDateString().slice(0,3)
might return anything. Far simpler is to use the built–in getDay method. If you must use a switch statement, then:
switch (date.getDay())
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
...
but
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var day = days[date.getDay()];
is much less to type.

Showing Invalid Date in JavaScript

I created a Javascript logic to retrieve date and time from some values.
initially i did was parsed the DateTime, convert it to string, then Split the string and retrieve the Date.
Like that i retrieved the time parsed, and atlast Joined all together(new Date + new Time).
I tried to convert it to date, now when i alert it then it says invalid Date. I want to display the newly created date just like this format.
var sampDate = new Date();
alert(sampDate);
Iam no good at explaining so iam uploading my code to fiddle and here also.
Please take a look at the JSFiddle. What i was done is below. Please point out what iam doing wrong with a detailed description. Any help will be very much appreciated.
JSFIDDLE : http://jsfiddle.net/5csge/
var date = 1745488627000;
var parsedDate = new Date(parseInt(date, 10)).toString();
var splitDate = parsedDate.split(" ");
var currentMonth;
switch (splitDate[1]) {
case "Jan":
currentMonth = 1;
break;
case "Feb":
currentMonth = 2;
break;
case "Mar":
currentMonth = 3;
break;
case "Apr":
currentMonth = 4;
break;
case "May":
currentMonth = 5;
break;
case "Jun":
currentMonth = 6;
break;
case "Jul":
currentMonth = 7;
break;
case "Aug":
currentMonth = 8;
break;
case "Sep":
currentMonth = 9;
break;
case "Oct":
currentMonth = 10;
break;
case "Nov":
currentMonth = 11;
break;
case "Dec":
currentMonth = 12;
break;
}
var time = -688627000;
var parsedTime = new Date(parseInt(time, 10)).toString();
var splitTime = parsedTime.split(" ");
var convertedEndDate = new Date(splitDate[2] + "/" + currentMonth + "/" + splitDate[3] + " " + splitTime[4]);
alert(convertedEndDate);
var currentDate = new Date();
alert(currentDate);
Your issue is here:
var convertedEndDate = new Date(splitDate[2] + "/" + currentMonth +
"/" + splitDate[3] + " " + splitTime[4]);
where you assume that 24/4/2025 00:42:53 can be passed as a parameter into a Date() object. From MDN:
dateString
String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).
This obviously isn't ISO8601 format (that would start 2025-04-24), but it also doesn't appear to be in the format of an RFC282 timestamp either. In fact, you're better off NOT translating the month name back into a number; the following appears to work perfectly, replacing the / with spaces:
var convertedEndDate = new Date(splitDate[2] + " " + splitDate[1]
+ " " + splitDate[3] + " " + splitTime[4]);
Use New Date - setFullYear() and setHours()
new Date()
setFullYear();
setHours();
DEMO UPDATED
Use date object and sets methods.
D = new Date();
D.setDay(12);
D.setMonth(2);
when you make this, the date will continue intervally after scripte is executed

dojo.ById not working

I have a calendar widget which is working OK. The problem I have is when selecting a date - the code doesn't find the field I want to set to the selected date, and I can't see why not.
<xp:panel id="calendarHolder">
<script>
require([ "dijit/Calendar", "dojo/date", "dojo/domReady!", "dijit/registry" ],
function(Calendar, date){
new Calendar({ value: new Date(),
onValueSelected: function(date){calendarDateClicked(date);
}},"mycal");
//Set month in correct format
function setMonth(month){
switch(month)
{
case 1:
month = "Jan";
break;
case 2:
month = "Feb";
break;
case 3:
month = "Mar";
break;
case 4:
month = "Apr";
break;
case 5:
month = "May";
break;
case 6:
month = "Jun";
break;
case 7:
month = "Jul";
break;
case 8:
month = "Aug";
break;
case 9:
month = "Sep";
break;
case 10:
month = "Oct";
break;
case 11:
month = "Nov";
break;
case 12:
month = "Dec";
break;
}
return month;
}
//create Click action
function calendarDateClicked(date){
var d = new Date(date);
var month = (d.getMonth() + 1);
month = setMonth(month);
var day = '' + d.getDate() + ",";
var year = d.getFullYear();
var dateString = [month,day,year].join(" ");
dojo.byId('#{id:hiddenCalWidgetSelectedDate}').value = dateString
dojo.byId('#{id:calDate}').value = dateString;
XSP.partialRefreshPost("#{id:mainPanel}",{
onComplete: function() {
XSP.partialRefreshGet("#{id:sideViews}", {});
}
});//Post Value to server
}
});
</script>
<div id="mycal">
</div>
<div id="textbox">
<xp:inputText id="hiddenCalWidgetSelectedDate"
style="display:block;" value="#{sessionScope.selectedDate}">
<xp:this.defaultValue><![CDATA[#{javascript://
var d = new Date(/*Today*/);
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day,month,year].join("/"); }]]></xp:this.defaultValue>
</xp:inputText></div>
</xp:panel>
The error I get is dojo.byId('#{id:hiddenCalWidgetSelectedDate}') is null
Any help would be appreciated.
Graeme
If you add a normal script block to an XPage, the EL will not get resolved.
You have to add your code inside a xp:scriptBlock.

Javascript date format without timezone

I have a javascript variable which is defined from an input value.
$d = $('#date').val();
$myDateParts = $d.split("-");
$dflip = new Date($myDateParts[2], ($myDateParts[1]-1), $myDateParts[0]);
console.log($dflip);
$dflip = Wed Sep 19 00:00:00 UTC+0100 2012
How can i format the output to just:
Wed Sep 19
You can do something using substring or toDateString or both
for e.g:
var dateString = new Date(2012, 0, 31).toDateString();
var noYear = dateString.substring(0, dateString.length-5);
console.log(noYear);
Try with following code.
<script src="../../ui/jquery.ui.datepicker.js"></script>
$( "#datepicker" ).datepicker( "D M yy", dflip.val());
This may not be the cleanest, most efficient or best way to accomplish what you're looking for, but I created a function to return the date without the timezone. You can adjust the "theDate" variable to return only the parts of the date you want.
function properDate(){
var d = new Date();
var DayOfMonth = d.getDate();
var DayOfWeek = d.getDay();
var Month = d.getMonth();
var Year = d.getFullYear();
var Hours = d.getHours();
var Minutes = d.getMinutes();
var Seconds = d.getSeconds();
switch (DayOfWeek) {
case 0:
day = "Sun";
break;
case 1:
day = "Mon";
break;
case 2:
day = "Tue";
break;
case 3:
day = "Wed";
break;
case 4:
day = "Thu";
break;
case 5:
day = "Fri";
break;
case 6:
day = "Sat";
break;
}
switch (Month) {
case 0:
month = "Jan";
break;
case 1:
month = "Feb";
break;
case 2:
month = "Mar";
break;
case 3:
month = "Apr";
break;
case 4:
month = "May";
break;
case 5:
month = "Jun";
break;
case 6:
month = "Jul";
break;
case 7:
month = "Aug";
break;
case 8:
month = "Sep";
break;
case 9:
month = "Oct";
break;
case 10:
month = "Nov";
break;
case 11:
month = "Dec";
break;
}
var theDate = day + " " + month + " " + DayOfMonth + " " + Year + " " + Hours + ":" + Minutes + ":" + Seconds;
return theDate;
}
My DateExtentions library will do that - although it may be overkill if all you're doing is that one, simple format.
http://depressedpress.com/javascript-extensions/dp_dateextensions/
I can parse the date based on a passed mask and format the output however you like (it'll also do all sorts of date math and utility stuff so again, it might be heavier than you need).

Categories