Convert a date in javascript - javascript

I need to convert the string date format from
Fri Feb 20 11:13:43 GMT 2015 to
2015/20/02 11:12
I used
var dateTest = new Date("Fri Feb 20 11:13:43 GMT 2015");
var yr = dateTest.getYear();
but yr seems to return "115"

Use
var yr = DateTest.getFullYear();

You want to use
var yr = dateTest.getFullYear();

Try This, Its Return full date and you can also change its format as you want
For Return Year
var d = new Date();
alert(d.getFullYear());
Return Full Date
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var output = (day < 10 ? '0' : '') + day + '/' +
(month < 10 ? '0' : '') + month + '/' +
d.getFullYear();
alert(output);
Here is Fiddle

Related

How to convert strings of the format "6 Dec, 2022 " to a date? [duplicate]

In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript.
The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM.
Hence this when converted to a datetime format and exported to excel, the column should be treat as a date.
Can any one of you help me to do it?
Cheers,
Other answers do not take into consideration this question is in a BIRT context.
Create a computed column in your dataset, with "Date time" as datatype
Enter as expression:
new Date(row["myDateStringField"]);
Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column.
That's it!
Checkout momentjs!
You can parse your time of any format like
moment("12-25-1995", "MM-DD-YYYY");
In your case, you don't even have to specify the format. It automatically recognizes it.
And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date.
http://jsfiddle.net/bbankes/d7SwQ/
var dateString = 'Fri 21 Feb 2014, 09:40 AM';
var date = new Date(dateString);
var yr = date.getFullYear();
var mo = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var hr = hours < 10 ? '0' + hours : hours;
var minutes = date.getMinutes();
var min = (minutes < 10) ? '0' + minutes : minutes;
var seconds = date.getSeconds();
var sec = (seconds < 10) ? '0' + seconds : seconds;
var newDateString = yr + '-' + mo + '-' + day;
var newTimeString = hr + ':' + min + ':' + sec;
var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do:
function stringToTimestamp(s) {
var t = s.match(/[\d\w]+/g);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
function pad(n){return (n<10?'0':'') + +n;}
var hrs = t[4] % 12;
hrs += /pm$/i.test(t[6])? 12 : 0;
return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' +
pad(hrs) + ':' + pad(t[5]);
}
console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD
new Date('2011-04-11T11:51:00');
or
new Date('2011-04-11');

How to convert a date with "nd","rd", "th" into a yyyy-mm-dd format Javasciript

I have an array of dates like:
dates=['2nd Oct 2014','20th Oct 2014','20th May 2019']
and I want to return them as an array in the YYYY-MM-DD format.
so far I have this:
function formatDate(dates) {
var t=[];
dates.map(function(date){
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
t.push([year, month, day].join('-'));
});
console.log(t);
return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));
but this gives me :
[NaN-NaN-NaN,NaN-NaN-NaN,NaN-NaN-NaN]
since its not able to recognize the date with "th", "nd".any idea how to fix this so that I get the o/p as:
[2014-10-02,2014-10-20,2019-05-20]
here is the fiddle: http://jsfiddle.net/nakpchvf/
Thanks!
If you're using moment, or if using it is an option, it's fairly simple:
const dates=['2nd Oct 2014','20th Oct 2014','20th May 2019'];
dates.forEach(date => {
console.log(moment(date, 'Do MMM YYYY').format('YYYY-MM-DD'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
Just remove letters.
function formatDate(dates) {
var t=[];
dates.map(function(date){
let datePieces = date.split(' ');
datePieces[0] = datePieces[0].replace(/\D+/g, '');
var d = new Date(datePieces.join(' ')),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
t.push([year, month, day].join('-'));
});
return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));
Basically above I take each date and split it into 3 different parts. I then fix the first index (the one causing an issue) by removing any non-numerical characters. After that I can recombine to form your date string :).
Without any external library and nevertheless compact:
function formatDate(d) {
return new Date(d.replace(/^(\d+)\w+/,"$1")).toLocaleString().replace(/^(\d+)\/(\d+)\/(\d+),.*$/, "$3-$2-$1")
}
console.log(['2nd Oct 2014','20th Oct 2014','20th May 2019'].map(formatDate))
If you are willing to obtain the result without using any external library, you can try like this using the concept of regular expressions for replacement of st, nd, rd, th kind of substrings with '' (blank string) from date strings in array.
I have also used ternary operator ?: for applying an inline if-else to convert month/date like 1 to 01 etc.
I have also used map() method defined on arrays to skip the use of loop.
function formatDates(dates) {
return dates.map((date) => {
const d = new Date(date.replace(/(st)|(nd)|(rd)|(th)/ig, ""));
const yyyy = d.getFullYear();
const mm = "" + (d.getMonth() + 1);
const dd = "" + d.getDate();
return `${yyyy}-${mm.length === 1? "0" + mm: mm}-${dd.length === 1? "0" + dd: dd}` ;
})
}
var dates = ['2nd Oct 2014', '20th Oct 2014', '20th May 2019']
console.log(formatDates(dates)); // [ '2014-10-02', '2014-10-20', '2019-05-20' ]
Just use replace() function to replace these words with empty like this
function formatDate(dates) {
var t=[];
dates.map(function(date){
var words=["th","nd"];
for(var i=0;i<words.length;i++){
date=date.replace(words[i],"");
}
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
t.push([year, month, day].join('-'));
});
console.log(t);
return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));

HTML Date : Get Correct date in yyyy - mm - dd

I am using HTML date function and javascript to get exact date in YYYY-mm-dd. its working fine for me except for 1st day of the month.
Ex: 1st Feb 2016 is converted to 2016-01-32
function mydate1(cachedDate) {
var today = new Date();
console.log(today);
if (cachedDate === undefined) {
console.log("no cached value found");
var d = new Date(document.getElementById("dt").value);
sessionStorage.setItem('dateCached', document.getElementById("dt").value);
console.log(d);
//sessionStorage.setItem('dropdownCached',document.getElementById("s1").value);
console.log("set session value :" + sessionStorage.getItem('dateCached'));
} else {
var d = new Date(cachedDate);
console.log(document.getElementById("dt").value);
sessionStorage.setItem('dateCached', d);
console.log("set session value :" + sessionStorage.getItem('dateCached'));
}
if (today < d) {
alert("No Record Found ..... ");
return;
}
dt = d.getDate();
dt++
dt = ('0' + dt).slice(-2);
mn = d.getMonth();
mn++;
mn = ('0' + mn).slice(-2);
yy = d.getFullYear();
var x = yy + "-" + mn + "-" + dt;
document.getElementById("ndt").value = dt;
ajaxFunction('dt');
console.log(x);
}
<input type="date" class="form-control" id="dt" onchange="mydate1();" />
<input type="text" id="ndt"/>
I tried couple of solutions from google but nothing is working for me .. can some one help me fixing the script.
First, you shouldn't need to increment the value returned by getDate(), because
the value returned by getDate() is an integer between 1 and 31.
This is in contrast to getMonth(), where
The value returned by getMonth() is an integer between 0 and 11.
Second, you might try specifying the time zone when you construct the new Date object:
var d = new Date(document.getElementById("dt").value + "(GMT)");
The Date.parse() method is implementation-dependent, so it's possible to encounter inconsistencies when parsing a date string. In my browser (Chrome 47), I see different Date objects if the string to parse includes a space at the end:
d = new Date("2016-02-01")
Sun Jan 31 2016 17:00:00 GMT-0700 (Mountain Standard Time)
d = new Date("2016-02-01 ")
Mon Feb 01 2016 00:00:00 GMT-0700 (Mountain Standard Time)
Although i was not able to find the exact bug in my above code .... but i managed to partially solve the problem (Need to add code to validate month > 12 and change year if required )
dt = d.getDate();
dt++
dt = ('0' + dt).slice(-2);
mn = d.getMonth();
mn++;
mn = ('0' + mn).slice(-2);
yy = d.getFullYear();
var x = yy + "-" + mn + "-" + dt;
var y = new Date(yy, mn, 0);
dd = y.getDate();
if (dd < dt) {
console.log("in test.....");
mn++;
mn = ('0' + mn).slice(-2);
var x = yy + "-" + mn + "-" + '01';
console.log("test" + x);
}

Javascript - Generate date from daynumber

Say I have the day number of the year.
How can I generate the date from that?
EX. Today's day number is 265
How can I get the output 9/23/2015?
Yesterday's day number was 264, how can I get the output of 9/22/2015?
Try like this
var year = 2015;
var date = new Date(year,0,1); // get the first date of year
var numberOfDaysToAdd=264;
date.setDate(date.getDate() + numberOfDaysToAdd); // add days to that date
console.log(date);
You may simply use Date():
var days = 265;
var now = new Date();
now.setMonth(0); // jan
now.setDate(days);
var date = 1 + now.getMonth();
var pad = function(v) {
return 10 > v ? '0' + v : v;
};
date = pad(date) + '/' + pad(now.getDate()) + '/' + now.getFullYear();
document.write(date);

Convert UTC Date to dd/mm/yyyy Format

I am having some difficulties when trying to convert UTC Date format to dd/mm/yyyy in JavaScript:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = new Date(date.toLocaleDateString());
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
I tried with this, but it returns me an invalid date. So I changed to this:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
However, it still returning me invalid Date. I wonder is there any possible way to change the date format of Fri May 31 2013 17:41:01 GMT+0200 (CEST) to dd/mm/yyyy?
Thanks in advance.
var d = new Date();
var n = d.toLocaleDateString();
This will be more superior in build JS method!
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
Try it:
Date.parseExact(Your_Date, 'dd/MM/yyyy').toString('MM/dd/yyyy');
or
Date.parseExact(Your_Date, 'MM/dd/yyyy').toString('dd/MM/yyyy');
Month is 0 indexed, but day is not. You don't need to add 1 to your day.
Also, you're formatting it for MM/dd/yyyy, not dd/MM/yyyy.
solution:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCDate())+ "/" + (d.getUTCMonth() + 1) + "/" + (d.getUTCFullYear()));
}

Categories

Resources