Showing Invalid Date in JavaScript - 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

Related

Why is path variable losing characters?

I have an API path where I need to have dates where the month is displayed as 2 digits. However, it keeps removing the zero to the left.
For example, when I get the date, if it's Jan through Sept, it only returns 1 digit. So I used the following code to add the extra zero:
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth();
let path = ``;
switch (month) {
case (month < 10):
month = `0${month}`;
path = `/v2/reports/time/team?from=${year}0${month}01&to=${year}0${month}31`;
break;
default:
path = `/v2/reports/time/team?from=${year}${month}01&to=${year}${month}31`;
break;
}
However, when the code actually runs, the path is always printing as so(which returns an error, because the zeros in front of the month in the date are removed):
/v2/reports/time/team?from=2021701&to=2021731
Should be this instead:
/v2/reports/time/team?from=20210701&to=20210731
What am I missing?
Switch implementation is not correct, so only default is execute, I will suggest you first explore the switch in JavaScript, this will help you in future as well,
however I have modified the code, please have a look below
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth();
let path = ``;
switch (true) {
case month < 10:
path = `/v2/reports/time/team?from=${year}0${month}01&to=${year}0${month}31`;
break;
default:
path = `/v2/reports/time/team?from=${year}${month}01&to=${year}${month}31`;
break;
}
Why don't add zero directly into variable like that?
const date = new Date();
const year = date.getFullYear();
let month = (date.getMonth() < 10) ? '0' + date.getMonth() : date.getMonth();
let path = `/v2/reports/time/team?from=${year}${month}01&to=${year}${month}31`;
console.log(path);

php Date Conversion to 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>

Date to String object conversion

I have use the following code snippet to convert the Date object to string .
var startDate = new Date();
var result = Globalize.parseDate(startDate, "MM/DD/YYYY");
but it will return the null value. How to convert the Date object to string specific format ?
To know all possible ways, check this link out.
I've put all the DEMOS here...
STANDARD JS:
<script type="text/javascript">
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months start with zero
var curr_year = d.getFullYear();
document.write(curr_month + "/" + curr_date + "/" + curr_year);
</script>
MOMENT.JS:
Download here...
<script>
var a = moment([2010, 1, 14, 15, 25, 50, 125]);
a.format("MM/DD/YYYY,");
</script>
Don't want to download, simply add this line:
<script src="http://momentjs.com/downloads/moment.min.js"></script>
jQuery UI:
$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));
IE:
var d1=new Date();
d1.toString('MM-dd-yyyy');
Globalize:
var startDate = new Date();
var result = Globalize.format(startDate, "MM/DD/YYYY");
I assume that you are using Globalize.
What you should do is to format the date, not parse it.
var startDate = new Date();
var result = Globalize.format(startDate, "MM/DD/YYYY");
You can simply use
var startDate = new Date();
alert((startDate .getMonth() + 1) + '/' + startDate .getDate() + '/' + startDate .getFullYear());
DEMO
Try this:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
Reference: Where can I find documentation on formatting a date in JavaScript?
MomentJS has a very robust set of time formatting options, you can use them.
Below is the example how it will work in your case
moment(stateDate).format("MM/DD/YYYY");
This function takes a date object as a parameter and returns a string in MM/DD/YYYY format :
function format(date) {
return [
('0' + (date.getMonth() + 1)).slice(-2),
('0' + date.getDate()).slice(-2),
date.getFullYear()
].join('/')
}
Usage example (gives today's date in MM/DD/YYYY format) :
format(new Date) // "01/03/2014"
You can easily change the resulting format with a few modifications :
function format(date) {
return [
date.getDate(),
date.getMonth() + 1,
('' + date.getFullYear()).slice(-2)
].join('-')
}
Usage example (gives today's date in D-M-YY format) :
format(new Date) // "3-1-14"
Playing around
I've tuned the function a bit, this might be interesting for very basic needs :)
function format(date, format) {
var i = 0, bit;
if (!format) format = 'MM/DD/YYYY'; // default
format = format.split(/([^DMY]+)/i);
while (bit = format[i]) {
switch (bit.charAt(0).toUpperCase()) {
case 'D': format[i] = date.getDate(); break;
case 'M': format[i] = date.getMonth() + 1; break;
case 'Y': format[i] = date.getFullYear(); break;
}
if (bit.length === 2) {
format[i] = ('0' + format[i]).slice(-2);
}
i += 2;
}
return format.join('');
}
Usage examples :
format(new Date) // "01/03/2014" (default)
format(new Date, 'd/m/y') // "3/1/2014"
format(new Date, 'D/M/Y') // "3/1/2014"
format(new Date, 'DD-MM-YY') // "03-01-14"
format(new Date, 'M/YY') // "1/14"

Format Date from String in javascript

I have a string that has a date in it and I wan't to be able to convert it.
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "-" + day + "-" + year;
alert(shortStartDate);
I want it so it converts March-09-2010 to 09-03-10 (DD-MM-YY)
Anyone know what I am doing wrong?
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate.replace(/-/g, "/")); // replace hyphen with slash
var month = convertedStartDate.getMonth() + 1
var date = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = date + "-" + month + "-" + year;
alert(shortStartDate);
demo: http://jsfiddle.net/BjnBW/
Try this:
var dt=Date.parse(Yourstring);
formatDate('DD-MM-YY',dt);
Please check this Date.parse
Check your syntax changed your code a little, modify it according to it then ---
var startDate = "March/09/2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = day+ "-" + month+ "-" + year;
alert(shortStartDate);
your date string is not in the correct format. for correct formats, please see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
try this or jsfiddle
var startDate = "March-09-2010";
var tmp = startDate.split('-');
tmp.splice(1, 0, ',');
var convertedStartDate = new Date(tmp.join(' '));
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = ('0' + day).slice(-2) + "-" + ('0' + month).slice(-2) + "-" + year;
alert(shortStartDate);
var shortStartDate =
Globalize.format(Globalize.parseDate(startDate, 'MMMM-dd-yyyy'), 'dd-MM-yy');
Use some library to do the conversion, because the built-in Date.parse() is implementation-dependent. It depends on the system locale what formats it accepts.
The code above uses Globalize.js, which can handle a large number of date formats, including formats with month names in different languages (the default being English).
You'll need to convert 'March' to a number. One way is to use this Array extension to be able to retrieve a month number from a month name:
Array.prototype.enum = function(){
var obj = {};
for (var i=0; i<this.length; (i+=1)) {
obj[this[i]] = i;
}
this.enum = obj;
return this;
};
Now, create an Array with month names
var months = ('January,February,March,April,May,June,July,'+
'August,September,October,November,December').split(',')
.enum();
Now you rewrite your date:
var startDate = "March-09-2010".split(/\-/),
month = months.enum[startDate[0]]+1;
startDate = [startDate[1],
month < 10 ? '0'+month : month,
startDate[2]].join('-');
//=> startDate now is: '09-03-2010'
Use getDateFromFormat() to convert string to date in javascript.
Check this link for more help: http://www.mattkruse.com/javascript/date/

JavaScript Date / Time Conversion

I have dates and times in a database in the following format:
2011-08-02T00:00:00-00:00
What is the easiest way to convert them to something like 8-2-2011?
Thanks,
var date = "2011-08-02T00:00:00-00:00".split('T')[0].split('-').reverse();
var month = date[0], day = date[1];
//remove 0 in the beginning if not necessary
if (+month < 10) {
month = month.slice(1);
}
if (+day < 10) {
day = day.slice(1);
}
//swap between the two
date[0] = day;
date[1] = month;
date.join('-');
Or you can use the boring Date way.
Here's the code:
x=new Date("2011-08-02T00:00:00-00:00")
str=(x.getUTCMonth()+1)+"-"+x.getUTCDate()+"-"+x.getUTCFullYear()
Or:
x="2011-08-02T00:00:00-00:00"
x=/^(\d+)\-(\d+)\-(\d+)/.exec(x)
if(x){
str=(parseInt(x[2],10)+"-"+parseInt(x[3],10)+"-"+parseInt(x[1],10))
}
This format will work in the Javascript Date constructor:
var d = new Date("2011-08-02T00:00:00-00:00");
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var output = month + "-" + day + "-" + year;
one way could be to split up the date part
var date = "2011-08-02T00:00:00-00:00";
var dpart = (date.substr(0,10)).split("-");
var odate = parseInt(dpart[1],10)+"-"+parseInt(dpart[2],10)+"-"+dpart[0];

Categories