JavaScript convert number to date to compare against current date - javascript

Hi i have been working on the final question for my assignment and i have to check if today's date is greater than a date that is store as a number in a database. ie today's date would be 16122017 dd mm yy as you can see it has no spaces or a "-" or "/" just a number. i can get todays date reverse it and remove the - but a simple < or > does not work for comparison as they are numbers not java date formats.
So i figure i have to add the - back into the date and reverse it so it yy mm dd and then compare it to the current date.
Can any one show me how to add - into the number format, i can simply reverse it back to yy mm dd from dd mm yy once done with
> c = c.split('-').reverse().join('');
where c is the var containing the number date. i assume once it has - back in it i could just do
if (c > LocalDate.now())
or do i need to assign it to a new date var ?

There are some cool addon packages like moment.js that can do this with an elegant call. But, in native javascript you can do this sort of thing, using the handy-dandy setFullYear(y,m,d) function.
var ds = '16122017'
var myDate = new Date();
myDate.setFullYear(ds.substring(4,8),ds.substring(2,4)-1,ds.substring(0,2));
var today = new Date();
today.setHours (0,0,0,0); /* turn now into today */
if (myDate < today) {
/* myDate was before today */
}

Besides using a library that can convert the dates for you, I suggest the good old substring method if you know for sure that the first two numbers are the day, then month, then year, such that
var day = str.substring(1, 2);
and so on. Then you create a new Date object based on your calculations and work with it.
If your input doesn't have trailing zeros, that adds complexity to the problem, but nothing that you can't overcome.

Related

How to get date & time using moment.js

I need to get the start date and end date in the below format using moment js
startDate = 20160427000000 and
endDate = 20160427235959
Here the start date appended with 000000 and end date appended with 235959
What is the right way to get this result in javascript
You want the format operator. Since it looks like your 0's and 2359's are hardcoded (I assume you're doing start and end of days), try:
startDate = moment().format('YMMDD000000');
endDate = moment().format('YMMDD235959');
EDIT: Or, as RobG pointed out, you can use:
startDate = moment().startOf('day').format("YMMDDHHmmss");
endDate = moment().endOf('day').format("YMMDDHHmmss");
(Which is much neater)
I'm totally confused, I don't know if you want to parse the format or output it. If you want to parse dates using moment.js in that format, then in time zone +05:30:
// Format YYYYMMDDHHmmss for 2016-04-26T00:00:00
var s = '20160426000000';
var x = moment(s, 'YYYYMMDDHHmmss');
// Show date in ISO 8601 extended format
console.log(x.format()); // 2016-04-26T00:00:00+05:30
To shift to the end of the day and output in YYYMMDDHHmmss format:
console.log(x.endOf('day').format('YYYYMMDDHHmmss')); // 20160426235959
In the format string:
YYYY is 4 digit year
MM is two digit month
DD is two digit day
HH is two digit hour in 24 hour format
mm is two digit minute
ss is two digit seconds
For Getting Format Like these in moment.js - (2020-12-15T13:00:00)
let a =2023-01-14T20:15:00-05:00
You can use moment(a).format("YYYY-MM-DDTHH:mm:ss")
Result: 2023-01-14T20:15:00

Convert string to datetime in javascript and compare with current time

I am trying to pick up value from datetimepicker tetxbox and compare those values with current time.
JSFiddle
//startTime textbox text = 19/12/2014 03:58 PM
var startTime = Date.parse($('[id$=txtStartDate]').val().toString());
//endTime textbox text = 19/12/2014 04:58 PM
var endTime = Date.parse($('[id$=txtEndDate]').val().toString());
var currentTime = Date.now();
alert(startTime);
alert(endTime);
alert(currentTime);
if (currentTime >= startTime && currentTime <= endTime) {
alert();
}
Date.parse() is used fro converting string to milliseconds since Jan 1 1970.
Date.now() returns current date milliseconds since Jan 1 1970.
But the above conversion methods are not working properly.
What should be logic to compare datetime by first sonverting string in format like 19/12/2014 03:58 PM to Date object and then do comparing.
The problem is Date() expects date format mm/dd/yyyy, so your date is invalid.
You can fix your date like this:
function toValidDate(datestring){
return datestring.replace(/(\d{2})(\/)(\d{2})/, "$3$2$1");
}
var startTime = Date.parse(toValidDate($('[id$=txtStartDate]').val().toString()));
var endTime = Date.parse(toValidDate($('[id$=txtEndDate]').val().toString()));
var currentTime = Date.now();
alert(startTime);
alert(endTime);
alert(currentTime);
DEMO: http://jsfiddle.net/3mztdaja/3/
Since that format isn't documented as being supported by Date.parse, your best bet is to parse it yourself, which isn't difficult: Use String#split or a regular expression with capture groups to split it into the individual parts, use parseInt to convert the parts that are numeric strings into numbers (or, with controlled input like this, just use the unary + on them), and then use new Date(...) to use those numbers to create a Date instance.
One gotcha: The month value that new Date expects is zero-based, e.g. 0 = January. Also remember to add 12 to the hours value if the input uses AM/PM instead of the 24-hour clock.
Or, of course, use any of several date/time handling libraries, such as MomentJS.
You should use this method
var startTime = new Date(year, month, day, hours, minutes, seconds, milliseconds);
this a demo http://jsfiddle.net/hswp7x8k/
to extrat value from string you can use this method
dd = '19/12/2014 03:58';
dd.match(/(\d+)\/(\d+)\/(\d+)\s*(\d+):(\d+)/);
this a demo http://jsfiddle.net/w3wow1ay/2/

Date to epoch and vice versa - JavaScript

I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

Jquery Date.parse returning NaN in Chrome browser?

I have a senario where i have to parse two dates for example start date and end date.
var startdate = '02/01/2011';
var enddate = '31/12/2011';
But if we alert start date
alert(Date.Parse(startdate)); i will get 1296498600000
but if i alert enddate
alert(Date.Parse(enddate)); i will get NaN
But this is working in other browsers except Chrome, But in other browsers
alert(Date.Parse(enddate)); i will get 1370889000000
Can anybody know a workaround for this?
If you want to parse a date without local differences, use the following, instead of Date.parse():
var enddate = '31/12/2011'; //DD/MM/YYYY
var split = enddate.split('/');
// Month is zero-indexed so subtract one from the month inside the constructor
var date = new Date(split[2], split[1] - 1, split[0]); //Y M D
var timestamp = date.getTime();
See also: Date
According to this
dateString
A string representing an RFC822 or ISO 8601 date.
I've tried your code and I also get NaN for the end date, but if i swap the date and month around, it works fine.

Categories

Resources