I'm using Pikaday, which requires Moment.js to format dates. This allows easy date formatting:
var picker = new Pikaday({
format: 'YYYY-MM-DD'
});
However, when I include the Pikaday npm package, Moment.js is over 40kb. Literally all I need it for is to change the date format to YYYY-MM-DD from the practically unusable default Pikaday format.
Can I do this without having to include a 40kb library?
If you want to use only format YYYY-MM-DD, you can build the date string using native Date methods:
const picker = new Pikaday({
field: document.getElementById('datepicker')
,onSelect: date => {
const year = date.getFullYear()
,month = date.getMonth() + 1
,day = date.getDate()
,formattedDate = [
year
,month < 10 ? '0' + month : month
,day < 10 ? '0' + day : day
].join('-')
document.getElementById('datepicker').value = formattedDate
}
})
Demo
const picker = new Pikaday({
field: document.getElementById('datepicker')
,onSelect: date => {
const year = date.getFullYear()
,month = date.getMonth() + 1
,day = date.getDate()
,formattedDate = [
year
,month < 10 ? '0' + month : month
,day < 10 ? '0' + day : day
].join('-')
document.getElementById('datepicker').value = formattedDate
}
})
#import url("https://rawgit.com/dbushell/Pikaday/master/css/pikaday.css");
<script src="https://rawgit.com/dbushell/Pikaday/master/pikaday.js"></script>
<input type="text" id="datepicker">
I wrote a small formatter a while ago after seeing the date-formatter.js formatter and parser, maybe it will suit. It's pretty much self–documenting:
function formatDate(date, format) {
var tokens = ['d', // day number, e.g. 3, 12
'dd', // day number padded to two digits, e.g. 03, 12
'ddd', // day name abbreviated, e.g. Mon, Tue
'dddd', // day name in full, e.g. Monday, Tuesday
'M', // month number, e.g. 5, 10
'MM', // month number padded to two digits, e.g. 05, 10
'MMM', // month name abbreviated, e.g. May, Oct
'MMMM', // month name in full, e.g. May, October
'y', // Year, e.g. 71, 2011
'yy', // Year as two digits, e.g. 71, 11
'yyy', // Year as three digits, e.g. 071, 011
'yyyy', // Year padded to 4 digits, e.g. 0071, 2011
'h', // Hour, e.g. 1, 12
'hh', // Hour padded to two digits, e.g. 01, 12
'm', // Minute, e.g. 1, 23
'mm', // Minute padded to two digits, e.g. 01, 23
's', // Second, e.g. 1, 15
'ss', // Second padded to two digits, e.g. 01, 15
'ap', // 12 hour time lower case, e.g. 1:45 am, 12:30 pm
'AP', // 12 hour time upper case, e.g. 1:45 AM, 12:30 PM
'z', // Return values and "z" timezone
'Z', // Return values and "Z" timezone
'tz', // Append timezone as +/-00:00
'TZ']; // Append timezone as +/-00:00
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
// Generate all the parts as strings
var parts = {d : '' + date.getDate(),
dd : ('0' + date.getDate()).slice(-2),
ddd : days[date.getDay()].slice(0,3),
dddd : days[date.getDay()],
M : '' + (date.getMonth() + 1),
MM : ('0' + (date.getMonth() + 1)).slice(-2),
MMM : months[date.getMonth()].slice(0,3),
MMMM : months[date.getMonth()],
y : '' + date.getFullYear(),
yy : ('0' + date.getFullYear()).slice(-2),
yyy : ('00' + date.getFullYear()).slice(-3),
yyyy : ('000' + date.getFullYear()).slice(-4),
h : '' + date.getHours(),
hh : ('0' + date.getHours()).slice(-2),
m : '' + date.getMinutes(),
mm : ('0' + date.getMinutes()).slice(-2),
s : '' + date.getSeconds(),
ss : ('0' + date.getSeconds()).slice(-2)};
// Parse format character by character and build string
var b = format.split('');
var formattedString = '';
var token = '';
for (var i = 0, iLen = b.length; i < iLen; i++) {
token += b[i];
if (tokens.indexOf(token + b[i+1]) == -1) {
if (tokens.indexOf(token) != -1) {
formattedString += parts[token];
} else {
formattedString += token;
}
token = '';
}
// console.log(token + ' : ' + formattedString);
}
return formattedString;
}
['yyyy-MM-ddThh:mm:ss',
'yyyyMMTddhhmm',
'dddd, d MMMM, yyyy at hh:mm:ss'
].forEach(function (s) {
document.write('<br>' + formatDate(this, s));
}, new Date());
Try this if you're using /uglify or other compilers this might work better for you.
onSelect: function(date) {
//Format here
}
Instead of
onSelect: date => {
//Format here
}
you can also do the following
new Pikaday({
field: document.getElementById('eDate'),
toString: function(date) {
var parts = [('0'+date.getDate()).slice(-2), ('0'+(date.getMonth()+1)).slice(-2), date.getFullYear()];
return parts.join("-");
}
})
this will produce 18-07-1980. You can change from '-' to '/' by changing return parts.join("-"); and you can rearrange parts to apply mm/dd/yyyy via parts array
Related
How can i convert the date i get from DB to a certain format.?
this is what I get, 2021-03-30T17:57:53.489Z
I want it to be in format of dd/mmm/yyyy hh:mm in my localtime.
expected output : 30/03/2021 11:27 PM
what I tried so far,
const formatDate = (date) => {
let data = new Date(date);
data = data.toLocaleString('rm-CH', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
return data;
};
console.log(formatDate('2021-03-30T17:57:53.489Z'))
on jsfiddle i get the output like "30-03-2021 23:27"
but on my React native app, when I try this I get output like Tue mar 30 23:27:53 2021.
can someone help me out here.?
PS: My Timezone is India, GMT +5.30. the date string is what I get from my DB(create_date, Postgresql)
A one-liner with fancy string manipulation (spread out to make more readable):
console.log(
new Date()
.toISOString()
.replace(/-/g, '/')
.replace('T', ' ')
.split(':')
.slice(0, -1)
.join(':')
.split(' ')
.map((a, i) => i === 0 ? a.split('/').reverse().join('/') : a)
.join(' ')
);
Or you could just calculate it manually:
const date = new Date(),
pad = (num) => num.toString().length < 2 ? `${'0'.repeat(2 - num.toString().length)}${num}` : num;
console.log(
`${pad(date.getDate())}/${pad(date.getMonth())}/${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}`
);
Or take a shortcut and use a library like Moment.
console.log(
moment().format('DD/MM/yyyy HH:mm')
);
<script src="https://momentjs.com/downloads/moment.js"></script>
I actually figured out a way,
function formatDate() {
var d = new Date('2021-03-30T17:57:53.489Z'),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear(),
hour = d.getHours(),
min = d.getMinutes();
var ampm = hour >= 12 ? 'pm' : 'am';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
min = min < 10 ? '0'+min : min;
var strTime = hour + ':' + min + ' ' + ampm;
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return `${day}-${month}-${year} ${strTime}`
}
output : 30-03-2021 11:27 pm
I have a start date 4/10/2021 and end date 4/12/2021
I want get Tuesday, Thursday and Friday date in jquery
I found this solution:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;
//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
if (x.getDay() == 5) {
$("#append_text").append("Date : " + x.getDate() + "/"
+ (x.getMonth() + 1) + "<br>");
x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
j = 7;
count++;
} else {
j = 1;
x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
}
}
$("#append_text").append("total fridays : " + count + "<br>");
but it return only Friday and i think it doesn't work truly
The result is:
Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
The solution link is here:
Get Friday Dates of Year in javascript using jquery
do you have any solution for that?
As mentioned in getDay() docs:
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So, clearly
if (x.getDay() == 5)
5 here stands for Friday. So, if you also need Tuesday as 2 & Thursday as 4, you simply need to modify for loop like:
var day = x.getDay();
if (day === 2 || day === 4 || day === 5)
Demo:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var html = '';
var count = 0;
//getting the all fridays in a financial year
for (var i = 0; x < y; i++) {
var day = x.getDay();
if (day === 2 || day === 4 || day === 5) {
html += "Date : " + x.getDate() + "/" + (x.getMonth() + 1) + "<br>";
if (day === 5)count++;
}
x.setDate(x.getDate() + 1)
}
$("#append_text").append(html);
$("#append_text").append("total fridays : " + count + "<br>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=append_text></div>
Try this.
var start = new Date(2021, 10, 04);
var end = new Date(2021, 12, 04);
var tuesdays = [], thursdays = [], fridays = [];
for (var current = start; current <= end; current.setDate(current.getDate() + 1)) {
var day = current.getDay();
switch (day) {
case 2: // tuesdays
tuesdays.push(formatDate(current));
break;
case 4: // thursdays
thursdays.push(formatDate(current));
break;
case 6: // fridays
fridays.push(formatDate(current));
break;
default: //other dates
break;
}
}
function formatDate(d) { // formats date to dd/mm/yyy
return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
}
console.log(tuesdays.length + " Tuesdays: ", tuesdays.join('\t'));
console.log(thursdays.length + " Thursdays: ", thursdays.join('\t'));
console.log(fridays.length + " Fridays: ", fridays.join('\t'));
You can do this by iterating over every date between the two dates and saving the ones that fit some criterion, or you can get the first of the required dates, then add 7 days to get each weekly until the end date, e.g.
// Parse date in day/month/year format
function parseDMY(s) {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get next day by dayNumber on or after date, default today
function getDayOfWeek(day, date) {
let d = date? new Date(+date) : new Date();
d.setDate(d.getDate() - d.getDay() + day +
(day < d.getDay()? 7 : 0));
return d;
}
// Format date as dd/mm/yyyy
function formatDMY(date) {
return date.toLocaleString('en-GB', {
year : 'numeric', // remove if year not required
month: '2-digit',
day : '2-digit'
});
}
// Given start and end date, get days by day number between
// dates inclusive
function getDaysBetweenDates(d0, d1, ...days){
let dStart = parseDMY(d0);
let dEnd = parseDMY(d1);
// Guard against endless loop
if (dEnd < dStart) return;
let dates = [];
while (dStart <= dEnd) {
days.forEach(day => {
let d = getDayOfWeek(day, dStart);
if (d <= dEnd) dates.push(formatDMY(d));
});
dStart.setDate(dStart.getDate() + 7);
}
return dates.sort(
(a, b) => a.split(/\D/).reverse().join('').localeCompare(
b.split(/\D/).reverse().join(''))
);
}
// Get all Tue, Thu and Fri between 4 Oct 2021 and 4 Dec 2021 inclusive
console.log(getDaysBetweenDates('4/10/2021', '4/12/2021', 2, 4, 5));
I've left the year in the date, it's easily removed by removing year: 'numeric', from the formatting options.
Note that in the OP:
y.setFullYear(2021, 12, 04);
creates a Date for 4 Jan, 2022 not 4 Dec 2021 because months are zero indexed, so December is 11. A month value of 12 rolls over to January of the following year.
I have a requirement to validate start-date < end-date, but the date formats changes based on the regional settings.
User can change region of site at any time when user changes to different date formats by validation fails.
I get error if the format is of 19-2-1
function getFormattedDate(datestr) {
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 month + '/' + day + '/' + year;
}
//date format for all regions (mm-dd-yyyy, dd-mm-yyy, d mm yyyy, mm dd yyyy, mm/dd/yyyy, dd/mm/yyyy, dd.mm.yyyy, mm.dd.yyyy)
if (isNaN(StartDateEnfant.valueOf()) || isNaN(OData__EndDateEnfant.valueOf())) {
StartDateEnfant = new Date(startDate.replace(/(\d{2})[- /.](\d{2})[- /.](\d+)/, "$2/$1/$3"));
OData__EndDateEnfant = new Date(endDate.replace(/(\d{2})[- /.](\d{2})[- /.](\d+)/, "$2/$1/$3"));
}
I get wrong validation if start date is 3.1.2019(jan 3 2019) and end date if 10.1.2019 ( jan 10 2019) but it takes as sep 10 2019 which is wrong
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));
I am using the HTML5 element datetime-local. I need to have two formats of the date. One as a date object the other as a string. I am going to store the date object in the database and I am going to use the string to set the datetime-local form input.
I need to convert this string to a date object:
"2014-06-22T16:01"
I can't seem to get the correct time. This is what I am getting. The time not correct.
Sun Jun 22 2014 09:01:00 GMT-0700 (PDT)
This is the how I am formating the date:
function formatTime(_date) {
var _this = this,
date = (_date) ? _date : new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
seconds = date.getSeconds(),
function addZero(num) {
return num > 9 ? num : '0' + num;
}
minute = addZero(minute);
seconds = addZero(seconds);
hour = addZero(hour);
day = addZero(day);
month = addZero(month);
return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
};
Example:
http://codepen.io/zerostyle/pen/gwpuK/
If you are trying to get an ISO 8601 date string, you can try Date.prototype.toISOString. However, it always uses UTC. If you want to include the local timezone, use something like the following:
/* Return a string in ISO 8601 format with current timezone offset
** e.g. 2014-10-02T23:31:03+0800
** d is a Date object, or defaults to current Date if not supplied.
*/
function toLocalISOString(d) {
// Default to now if no date provided
d = d || new Date();
// Pad to two digits with leading zeros
function pad(n){
return (n<10?'0':'') + n;
}
// Pad to three digits with leading zeros
function padd(n){
return (n<100? '0' : '') + pad(n);
}
// Convert offset in mintues to +/-HHMM
// Note change of sign
// e.g. -600 => +1000, +330 => -0530
function minsToHHMM(n){
var sign = n<0? '-' : '+';
n = Math.abs(n);
var hh = pad(n/60 |0);
var mm = pad(n%60);
return sign + hh + mm;
}
var offset = minsToHHMM(d.getTimezoneOffset() * -1);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
'.' + padd(d.getMilliseconds()) + offset;
}
console.log(toLocalISOString(new Date())); // 2014-06-23T07:58:04.773+0800
Edit
The above probably misses your question, which seems to be;
I need to convert this string to a date object: "2014-06-22T16:01"
Presumaly you want to treat it as a local time string. ECMA-262 says that ISO–like strings without a timezone are to be treated as UTC, and that is what your host seems to be doing. So you need a function to create a local Date object from the string:
function parseYMDHM(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]||0, b[6]||0);
}
console.log(parseYMDHM('2014-06-22T16:01')); // Sun Jun 22 16:01:00 UTC+0800 2014