Convert Returned String (YYYYMMDD) to Date - javascript

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?

Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.

If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM

To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))

...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Related

How to get date after n number of days in a date range?

Suppose I have a start date which is 3/Sep/2019 and end date 10/Sep/2019.
I want to get the date after 4 days from the starting date. So if my starting date is 3/sep/2019 I want to get 7/Sep/2019 but not 12/sep/2019 since this date comes after my end date.
How can I achieve this?
So far I'm getting dates after n number of dates like this:
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
date = new Date(res);
alert(date);
var days = 7;
var date = new Date();
var res = date.setDate(date.getDate() + days);
This is how you get a day 7 days after the date you already have. It wraps to the next month when appropriate as well.
Try the function I wrote below:
function getFutureDate(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
return date
}
const fourDays = getFutureDate(4)
console.log(fourDays)

Javascript slice method not working as expected

I wrote a simple javascript function which converts string to date (in format 'dd.MM.yyyy HH.mm').
For extracting parts of that string, I've used slice method.
What is strange to me is that only day is returned as expected. All other variables are simply empty strings.
What am I doing wrong?
(
function(){
alert(GetDateFromStringDateTime("20.04.2017 18:15"));
}
)();
function GetDateFromStringDateTime(dateStr){
var day = dateStr.slice(0,2);
var month = dateStr.slice(3,2);
var year = dateStr.slice(6,4);
var hour = dateStr.slice(11,2);
var minute = dateStr.slice(14,2);
return new Date(year,month,day,hour,minute);
}
Picture from console window (month, year, hour and minute are empty strings):
String#slice() use a start and end parameter which are both zero-based index
console.log(GetDateFromStringDateTime("20.04.2017 18:15"));
function GetDateFromStringDateTime(dateStr) {
var day = dateStr.slice(0, 2);
var month = dateStr.slice(3, 5);
var year = dateStr.slice(6, 10);
var hour = dateStr.slice(11, 13);
var minute = dateStr.slice(14, 16);
console.log(day);
console.log(month);
console.log(year);
console.log(hour);
console.log(minute);
return new Date(year, month, day, hour, minute);
}
Use String.prototype.substr instead of slice

Comparing two dates in JavaScript

I am currently trying to compare the launch_date with today's date. Let's say if the launch_date is within 3 years from today's date, it should perform something but I only managed to come out with some portion of the code:
var today = new Date();
var launch_date = 2011/10/17 00:00:00 UTC;
//if today's date minus launch_date is within 3 years, then do something.
Any guides? Thanks in advance.
To explicitly check for the three year range
var ld = new Date('2011/10/17 00:00:00 UTC')
if(today.getFullYear() - ld.getFullYear() < 3) {
//do something
}
This will fail on an invalid date string and possibly some other edge cases.
If you'll be doing a lot of date calculations I highly recommend Moment: http://momentjs.com/
you could always calculate the timespan in days and use that.
var getDays = function(startDate, endDate){
var ONE_DAY = 1000 * 60 * 60 * 24;
var difference = endDate.getTime() - startDate.getTime();
return Math.round(difference / ONE_DAY);
}
See this JsFiddle: http://jsfiddle.net/bj4Dq/1/
Try-
var today = new Date();
var launch_date = new Date("2011/10/17 00:00:00 UTC");
var diff = today.getYear() - launch_date.getYear();
if(diff <=3 )
alert("yes");
else
alert("no");
jsFiddle
you can create a Date object and invoke getTime() method (returns numer of milliseconds since 1970-01-01). Use one of this rows:
var yourDate = new Date(dateString) // format yyyy-mm-dd hh:mm:ss
var yourDate = new Date(year, month, day, hours, minutes, seconds, milliseconds)
After in the if statement use this condition:
var edgeDate = // new Date(dateString);
if ( (today.getTime () - yourDate.getTime ()) >= edgeDate.getTime() ){
// do something
}
Regards,
Kevin

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>

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

Categories

Resources