I wrote code for getting the coming Saturday. So I wrote like this and the result is 2020-03-07T04:00:48.306Z. I found the dateT~~. I just only need the date. I can use the split method, but I don't wanna use this. is there any other way?
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
Try with substr,
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff)).toISOString.substr(0,10);
}
Your getSaturday function returns a new Date object (which is the Saturday).
The simplest way is to use split to get the date string back
const d = getSaturday(...)
d.toISOString().split("T")[0]
But since you don't want to use split. You may want to use moment: a very popular and lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
And then you can rewrite your function like this:
function getSaturday(d) {
return moment(d).day("Saturday").format("YYYY-MM-DD")
}
console.log(getSaturday(new Date()))
<script src="https://momentjs.com/downloads/moment.js"></script>
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
function dateSaturday(d) {
var ds = [
d.getFullYear(),
((d.getMonth()+1) < 10) ? `0${(d.getMonth()+1)}` : (d.getMonth() +1).toString(),
(d.getDate() < 10) ? `0${d.getDate()}` : d.getDate().toString()
];
return ds.join("-")
}
console.log(dateSaturday(getSaturday("2020-03-04")));
Date
Related
Can you help me with this problem? I tried to make a function that receives a parameter of type Date e.g. 12.11.2020. I want it to return the previous day.
function getPreviousDay(d) {
var dateObj = new Date(d);
var previousDay = dateObj.setDate(dateObj.getDate() - 1);
return previousDay;
}
console.log(getPreviousDay(new Date())); //1606809601830
But as you see, the function returns: 1606809601830, I don't know why.
Thank you, guys!
A simple ES6 one-liner would be :
const getPreviousDay = d => d.setDate(d.getDate() - 1) && d
console.log(getPreviousDay(new Date()));
This function changes the day of the Date object you pass it, and returns it. No need to create an intermediary one.
Typescript version (with type checking, to make sure you always pass it a Date object, and not a string) :
const getPreviousDay = (d:Date): Date => d.setDate(d.getDate() - 1) && d
You don't want to return the result of Date.prototype.setDate() which is the date in milliseconds, you want to return the mutated dateObj
function getPreviousDay(d) {
var dateObj = new Date(d);
dateObj.setDate(dateObj.getDate() - 1);
return dateObj ;
}
console.log(getPreviousDay(new Date()));
This code return like this yesterday date(1.12.2020).
function getPreviousDay(d) {
var dateObj = new Date(d);
dateObj.setDate(dateObj.getDate()-1);
return dateObj.getDate() + '.' + (dateObj.getMonth()+1) + '.' + dateObj.getFullYear();
}
console.log(getPreviousDay(new Date()));
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.
Is there a way to make this date conversion accurately?
You need to specify the original format of the time, and then convert it to a new format.
const date = "02/16/2020";
alert(moment(date, "MM/DD/YYYY").format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use moment for date formatting:
Sample Code:
moment('02/16/2020').format('16/02/2020');
You can play with date by moment.js. It is very useful tool for javascript developer.
Momemet Js Document
For dynamic value:
moment(yourDate, 'MM/DD/YYYY').format('DD/MM/YYYY');
Here, yourDate is your dynamic value date.
check this. its work.
function formatDate(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;
return [day,month,year].join('/');
}
document.getElementById('res').innerHTML = formatDate('02/16/2020') ;
<div id="res">res</div>
2 || 1 liners ?
var src = '02/16/2020'
var a = src.split('/');
console.log(a.concat(a.splice(0, 2)).join('/'));
console.log(src.replace(/(\d+)\/(\d+)\/(\d+)/, '$3/$1/$2'));
If you want a conversion just between the exact formats you have mentioned:
function dfConvert(f) {
var farr = f.split("/");
return `${farr[1]}/${farr[0]}/${farr[2]}`;
}
var input = "02/16/2020";
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`);
If you want the actual date object and from that you want your mentioned format for some reason:
function toDate(f) {
var farr = f.split("/");
return new Date(parseInt(farr[2]), parseInt(farr[0])-1, parseInt(farr[1]))
}
function dfConvert(f) {
var d = toDate(f)
var day = d.getDate()
var month = (d.getMonth() + 1)
var year = d.getFullYear()
return `${((day.toString().length <= 1) ? "0": "")}${day}/${((month.toString().length <= 1) ? "0": "")}${month}/${year}`
}
var input = "02/16/2020"
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`)
Hope it helps
I am trying to know if a certain timestamp belongs to today, but I'm getting lost in Javascripts date management.
Is there any way to check if a timestampo belongs to the current day?
Simple check 1st timestamp of both days and compare them.
var ts = 1564398205000;
var today = new Date().setHours(0, 0, 0, 0);
var thatDay = new Date(ts).setHours(0, 0, 0, 0);
if(today === thatDay){
console.log("*** Same day ***");
}
It seems nasty-ish to me however you could do something similar to:
function isInToday(inputDate)
{
var today = new Date();
if(today.setHours(0,0,0,0) == inputDate.setHours(0,0,0,0){ return true; }
else { return false; }
}
This assumes you've already set your input date as a JS date. This will check if the two dates occur on the same day, and return true if so and false if not.
I'm sure someone will come along with a neater way to do this or a case where this fails but as far as I can see this should do the trick for you.
you can really depend on ISO date string with a substr function to compare the two strings
var T=1479288780873; /*assume your timestamp value*/
var theDay=new Date(T);
var today=new Date;
theDay.toISOString().substr(0,10) == today.toISOString().substr(0,10) ? console.log("same day"):null;
You can do something like this :
var day = 24 * 60 * 60 * 1000; //nb millis in a day
var todayTimestamp = new Date(year, month, day).getTime(); // Be careful month is 0 start
//OR
var todayTimestamp = new Date().setHours(0,0,0,0).getTime();
var diff = myTimestamp - todayTimestamp;
if ( diff >= 0 && diff <= day ) {
console.log("timestamp is today");
else {
console.log("timestamp is not today");
}
var timestamp = '2016-11-16 03:14:07.999999';
var datestamp = timestamp.substring(0, 10);
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(), mm, dd].join('-');
};
var date = new Date();
date.yyyymmdd();
console.log(String(datestamp) === String(date.yyyymmdd()));
It depends what format your timestamp is in.
But here is the most basic way to achieve this:
var today = new Date(year, month, day);
var timestamp = //your timestamp;
if (timestamp == timestamp){ //make sure the date formats are the same
//your code
}
I hope this is what you were looking for, there are more methods with the javascript date reference, don't hesitate to look it up.
How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript
<script type="text/javascript" language="javascript">
function disptextbox() {
var d = new Date();
var x = document.getElementById("ddlweeklist").value;
switch (x)
{
case "1":
document.getElementById("txtstart").value = d.toDateString();
document.getElementById("Txtend").value = d.toDateString();
break;
case "2":
var firstday = new Date(d.setDate(d.getDate() - d.getDay()));
var lastday = new Date(d.setDate(d.getDate() - d.getDay() + 6));
document.getElementById("txtstart").value= firstday.toDateString();
document.getElementById("Txtend").value = lastday.toDateString();
break;
case "3":
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.getElementById("txtstart").value = firstDay.toDateString();
document.getElementById("Txtend").value = lastDay.toDateString();
break;
case "4":
var firstd = new Date(d.getFullYear(), 0, 1);
var lastd = new Date(d.getFullYear(), 11, 31);
document.getElementById("txtstart").value = firstd.toDateString();
document.getElementById("Txtend").value = lastd.toDateString();
break;
}
}
</script>
in this code of implementation I want the date format to be in dd/mm/yyyy format ...I will be glad if any one help me over this this function call occurs on the drop down change especially...I am ok with functionality of the code but not comfortable in handling with DATE FUNCTIONS...
so please suggest me where I can get good examples for implementing date functions...in javascript
You can do this if you want dd/mm/yyyy format date:
new Date().toISOString().substr(0,10).replace(/(\d{4})-(\d{2})-(\d{2})/g,"$3/$2/$1");
I've written a couple of prototypes for dates than you may find useful:
Date.prototype.dateStr=function(split){
split=split===undefined?"-":split;
var output=parseInt(parseInt(this.getMonth())+1).toString().toLength(2);
output+=split;
output+=this.getDate().toString().toLength(2);
output+=split;
output+=this.getFullYear().toString().toLength(4);
return output;
}
Date.prototype.FOM=function(){
return new Date(this.getFullYear(),this.getMonth(),1);
}
String.prototype.toLength=function(len,fill){
fill=fill===undefined?"0":fill;
var outStr=this.toString();
while (outStr.length<parseInt(len)){
outStr=fill+outStr;
}
return outStr;
}
Technically, the 3rd one is a string prototype, but whatever. new Date().FOM() will give you a javascript date object for the first day of whatever month you pass it. new Date().dateStr("/") will give you a string - mm/dd/yyyy format - with separators as whatever you pass it, default "-".
That last one will take a string and make it a certain length by prepending the 'fill' - default '0'.
You could try with this function:
function toDateString(mydate) {
var day = mydate.getDate();
var month = mydate.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + mydate.getYear();
}
You could then use it this way:
alert(toDateString(firstday)); // I'm using alert just for demonstration purposes
Here is a DEMO you could fiddle with.
EDITED: Learning from #Helpful's answer below, my above function could be used as a prototype to better fit the way you wrote up your code like this:
Date.prototype.toDateString=function() {
var day = this.getDate();
var month = this.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + this.getYear();
}
so you could call it this way:
alert(thedate.toDateString()); // This is how you used it, if I understood it well.
Here is a DEMO of that.
Pass any data format
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
hope this will help you sure.....
Is it possible to determine if a date is a Saturday or Sunday using JavaScript?
Do you have the code for this?
Sure it is! The Date class has a function called getDay() which returns a integer between 0 and 6 (0 being Sunday, 6 being Saturday). So, in order to see if today is during the weekend:
var today = new Date();
if(today.getDay() == 6 || today.getDay() == 0) alert('Weekend!');
In order to see if an arbitrary date is a weekend day, you can use the following:
var myDate = new Date();
myDate.setFullYear(2009);
myDate.setMonth(7);
myDate.setDate(25);
if(myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');
You can simplify #Andrew Moore 's test even further:
if(!(myDate.getDay() % 6)) alert('Weekend!');
(Love that modulo function!)
The Date class offers the getDay() Method that retrieves the day of the week component of the date as a number from 0 to 6 (0=Sunday, 1=Monday, etc)
var date = new Date();
switch(date.getDay()){
case 0: alert("sunday!"); break;
case 6: alert("saturday!"); break;
default: alert("any other week day");
}
I think this is an elegant way to do this:
function showDay(d) {
return ["weekday", "weekend"][parseInt(d.getDay() / 6)];
}
console.log(showDay(new Date()));
Yes, it is possible, we can write a JavaScript code for that using JavaScript Date object.
Please use following JavaScript code.
var d = new Date()
document.write(d.getDay())
We can write a function to return the weekend in flag like below,
You can more customize the function to pass date. Or different return values for every day.
isItWeekEnd = function() {
var d = new Date();
console.log(d.getDay());
var dateValue = d.getDay();
// dateValue : 0 = Sunday
// dateValue : 6 = Saturday
if(dateValue == 0 || dateValue == 6)
return true;
else
return false;
}
var date = new Date();
var day = date.getDay();
if(day==0){
return false;
//alert('sunday');
}