Javascript: Get date string from raw date - javascript

I have another question on SO Unable to read date cell. This question is related to last question but more generic. How to convert Raw date, which represents number of days since 1st Jan 1900, to a javascript date type? [ Forget office365 ].
I have number of days elapsed since 1st Jan 1900. How can I get the date from it. For ex: I need a date after 42216 days, since 1st Jan 1900, How can I calculate that date? Answer is : 31-Jul-2015.

Try this:
(function(){
var date = new Date(1900,1,1);
var dayCount = 42216;
date.setDate(date.getDate() + dayCount)
console.log(date);
})()

Try this:
start = "01/01/1900"
newDate = start.split("/");
x = new Date(newDate[2]+"/"+newDate[1]+"/"+newDate[0]);
var numberOfDaysToAdd = 42216;
x.setDate(x.getDate() + parseInt(numberOfDaysToAdd));
var dd = x.getDate();
var mm = x.getMonth() + 1;
var yyyy = x.getFullYear();
var format = dd+'/'+mm+'/'+yyyy;
alert(format);
JSFIDDLE DEMO

Hope it help:
var dateStart= new Date('1900-01-01');
var afterDay=42216;
var newDay=new Date(dateStart.getTime() + afterDay*24*60*60*1000);
alert(newDay);

Related

How to format a date in JS

I have created a simple javascript to add 5 days to the current date. I am now having issues getting it to display the format day, date month i.e. Tue 7th Nov. Please can someone help
var newDt = new Date();
newDt.setDate(newDt.getDate() + 5);
document.writeln("" + newDt);
newDt.toDateString()
will return "Tue Nov 12 2017"
Alternatively, you can use a variety of date methods to build a date string that might be more amenable to your needs.
See date methods here:
https://www.w3schools.com/js/js_date_methods.asp
Try out this. If you want it in the format of Weekday Month Day Year remove the .slice(0, -5); on date.
There is plenty of documentation online. You have to look.
Read more about toDateString() here.
Read more about .slice() here.
var newDt = new Date();
newDt.setDate(newDt.getDate() + 5);
var date = newDt.toDateString();
document.writeln("" + date.slice(0, -5));
To make it in the format you want, Weekday Day Month use this example.
var date = new Date();
var locale = "en-us";
var weekdayNumber = date.toLocaleString(locale, { weekday: "short"});
var calenderDay = date.getDate();
var month = date.toLocaleString(locale, { month: "short" });
document.writeln(weekdayNumber + " " + calenderDay + "th " + month);
Be careful with dates like the 1st and 2nd or anything other than th

compare string with today's date in JavaScript

I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>

Get time difference in javascript ISO format

I have a datetime in ISO format i.e.
2012-06-26T01:00:44Z
I want to get the time difference from current time. How can I achieve this using javascript or javascript library Date.js or jquery
This will give you the difference in milliseconds, you can then format it as you want
var diff = new Date("2012-06-26T01:00:44Z") - new Date();
Try this:
var someDate = new Date("2012-06-26T01:00:44Z");
var now = new Date();
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((someDate.getTime()-now .getTime())/(one_day))
alert(diff)
Example fiddle
You can obviously amend the one_day variable to get the difference in the unit you require.
I would suggest converting ISO format to something that works cross browser.
Try this,
var d = "2012-06-26T01:00:44Z";
var someDate = new Date(d.replace(/-/g,'/').replace('T',' ').replace('Z',''));
alert(someDate - new Date());
Edit:
I guess, you need pretty time
Try this awesome code
Edit 2:
You needed reverse, so try this instead
var old_date = new Date();
alert('Old date: ' + old_date.toGMTString())
var new_date = new Date(old_date.setMinutes(old_date.getMinutes() - 5));
alert('Date 5 minutes before: ' + new_date.toGMTString());
If you need timestamp,
alert(new_date.getTime());
in order to format date you can use this function to get the desire format of the date and you can easily change the position of day , month and year.
function convertFormat(inputDate)
var date = new Date(inputDate);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
var fullYear = year + '/' + month + '/' + day
return fullYear;

Calculate the Date based on Current Date and No of Days using Javascript/Jquery

I need a help..
I have a Current Date and No of days column.
When i enter number of days,i should add current date plus no of days entered.
For example,
todays date 5th jan + 20(no of days) = 25th Jan 2011 in another column.
Kindly help me.
Thanks in Advance.
Date.js is fantastic for this.
Date.today().add(5).days();
As you are learning JavaScript you may find the w3schools site useful for simple examples of objects and functions that are exposed and how they may be used.
http://www.w3schools.com/jsref/jsref_obj_date.asp
You can calculate the date as follows:
var d = new Date(); // Gets current date
var day = 86400000; // # milliseconds in a day
var numberOfDays = 20;
d.setTime(d.getTime() + (day*numberOfDays)); // Add the number of days in milliseconds
You can then use one of the various methods of displaying the date:
alert(d.toUTCString());
You could do something like
Date.today().add(X).days();
Where X is the number of days the user has entered.
You can add dates like this in js:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
var month = someDate.getMonth() + 1; //Add 1 because January is set to 0 and Dec is 11
var day = someDate.getDate();
var year = someDate.getFullYear();
document.write(month + "/" + day + "/" + year);
See this p.cambell's answer here: How to add number of days to today's date?

how to increment date by giving the number of days in javascript

I want to increment dates using JavaScript I used .setDate(1) to increment dates by one day
but if the date is 31/11/2011 after increment becomes 1/0/2012,
the question is how to increment date by giving the number of days .
js
newDate.setDate(newDate.getDate()+1);
alert(newDate.getFullYear()+"-"+newDate.getMonth()+"-"+newDate.getDate());
That is correct, because in javascript, months are indexed from 0, not 1.
You need to alert like this instead:
alert(newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+newDate.getDate());
That is not wrong, given that months in Javascript dates range from 0 to 11. So when you speak of 31/11/2011, what javascript understands is 31/12/2011.
Lets make it some more clear:
var Date = new Date();
var DaysToAdd = 6;
someDate.setDate(Date.getDate() + DaysToAdd);
Formatting Date to dd/mm/yyyy format:
var dd = Date.getDate();
var mm = Date.getMonth() + 1;
var yyyy = Date.getFullYear();
var NewDate = dd + '/'+ mm + '/'+ yyyy;
Hope this helps.
You can use like this, Suppose you want to increment current date by 2 days then,
var today = new Date(); // Or Date.today()
var newDate = today.add(2).day();

Categories

Resources