populate textbox with formatted date - javascript

I have two datepicker fields (telerik, not jquery UI) and also a radio button list containing buttons for week, month, year, etc.
The user can either select a date range using the two datepickers, or alternatively, they can click one of the radio buttons and the fields should populate based on their choice.
So if the user selects week, the end date should be today and the start date should be 7 days ago.
What I have at the moment is this:
$(function () {
$("#dateRange_week").click(function () {
var now = new Date();
var startDate = now;
$("#StartDate").val(startDate);
$("#EndDate").val(now);
});
});
currently the jQuery inserted dates are strings formatted as follows
Tue Oct 02 2012 12:08:01 GMT-0400 (Eastern Daylight Time)
How do I calculate startDate as now - 7 days?
How can I format the dates as mm/dd/yyyy?
EDIT___
The fix:
Using Date.js as per the accepted answer below, the jQuery becomes
$("#dateRange_week").click(function () {
var startDate = (7).days().ago();
var start = startDate.toString("M/d/yyyy");
var endDate = new Date();
var end = endDate.toString("M/d/yyyy");
$("#StartDate").val(start);
$("#EndDate").val(end);
});

It's a pity, but JS doesn't have good datetime manipulation abilities.
Good news - you can use some plugin for that.
For example:
Moment - very good plugin from SO user timrwood
date.js - another good plugin for date and time manipulation
They both (and many others) have functions for adding/subtracting days and date formatting. And many other useful options.

Here is a good start for formatting the jQuery date jQuery date formatting
And this might help for subtracting days
Adding/Subtracting days from a date doesn't change the year/month correctly

Try something like:
DateTime dtNow = DateTime.Now;
DateTime dtBegin = DateTime.MinValue;
DateTime dtEnd = DateTime.MinValue;
dtBegin = dtNow.AddDays(1 - Convert.ToDouble(dtNow.DayOfWeek));
dtEnd = dtNow.AddDays(7 - Convert.ToDouble(dtNow.DayOfWeek));
To formate mm/DD/yyyy use .ToShortDateString()

Related

MomentJS - displaying now/ tomorrow instead of today/ tomorrow's date

I'm using a component from AntUI library that renders the date picker.
What I want to do is to display Now and Tomorrow instead of today's/ tomorrow's dates.
Is there a specific momentJS format (I couldn't find any, so probably not) or a way to configure momentJS library that it will automatically display those values instead of those dates?
You could check if the date is between moment().startOf('day'); and moment().endOf('day'); and display Now or Tomorrow depending on the result
moment().isBetween(moment().startOf('day'), moment().endOf('day'));
would be Now (true) and
moment().add(1, 'day').isBetween(moment().startOf('day'), moment().endOf('day'));
and this would be Tomorrow (false)
Try this:
var today = moment().endOf('day')
var tomorrow = moment().add(1, 'day').endOf('day')
var date = new Date();
//Check Today's date
if (date < today)
alert('today')
if (date < tomorrow)
alert('tomorrow')
UPDATE
You can use this as well but it will show current time as well:
moment().calendar(); // Today at 10:37 AM
moment().add(1, 'days').calendar(); // Tomorrow at 10:37 AM

Can not compare dates properly using Angular.js/Javascript

I need one help.I am unable to compare the selected date with today's date using Angular.js or JavaScript.I am explaining my code below.
var today=new Date();
console.log('2 dates',today,$scope.date);
From the above console i am getting the output like below.
2 dates Fri Jun 03 2016 18:29:16 GMT+0530 (India Standard Time) 03-06-2016
if(today > new Date($scope.date.split("-").reverse().join(","))){
alert('Please select future delivery date');
}
Here i need suppose my selected date is 03-06-2016 and today's date is 03-06-2016 the alert prompt should not come.But in my case its not happening like this.This alert message is coming also if selected date is 03-06-2016. Here i need the alert message should come if selected date is more than today's date only.Please help me.
Months are zero-indexed when constructing Dates:
console.log(new Date(2016,06,03));
"2016-07-03T04:00:00.000Z" // you expected June, but got July.
Note also that that is set to midnight: any new Date() run during the same day will be greater than that value.
String manipulation of dates is risky and error-prone, which is why everyone's knee-jerking momentjs at you (it is in fact a very good library and worth using if you're doing much date manipulation).
At the least, you may want to consider using a less ambiguous date format in $scope.date, but if you're stuck with that, in this case, you need to subtract 1 from the month when constructing a Date from it:
// this sample code will only work correctly on June 3 2016 :)
var $scope = {
date: "03-06-2016", // I am assuming DD-MM-YYYY format here
tomorrow: "04-06-2016"
};
var today = new Date();
// test against today:
var dArr = $scope.date.split('-');
var testDate = new Date(dArr[2],dArr[1]-1,dArr[0]);
if (today > testDate) {
console.log("today is greater than testDate.");
/* Note that anytime during today will be greater than the zero
o'clock constructed from $scope.date. If what you really want
is to alert only on the following day, then add 1 to the day
of $scope.date when converting it to a Date(). */
}
// now test against tomorrow:
dArr = $scope.tomorrow.split('-');
testDate = new Date(dArr[2],dArr[1]-1,dArr[0]);
if (today < testDate) {
console.log("today is less than (tomorrow's) testDate.");
}
Don't compare JavaScript dates using native < or > operators; install and use moment.js - it will handle all the difficulties for you:
if(moment(new Date()).isAfter(moment($scope.date, "MM-DD-YYYY"), 'day')) { ...
Convert to timestamp to compare it:
$scope.date = '2016-06-01';
var currentDate = new Date().valueOf();
var date = new Date($scope.date).valueOf();
if (currentDate > date) {
// something
}
It you use multi timezone, please convert both to a timezone.

Get MongoDB items matching date

I am trying to get a count on posted item from meteor-mongo matching date periods.
I inserted my posts dates as such.
posts
submitted: new Date()
the dates in the database have the following format.
yyyy-mm-dd 16:16:34.317Z // I do not understand the last part (what format it is)
I have tried this to get match the date of today from the submitted field
var currentDate = new Date();
var dd = currentDate.getDate();
var mm = currentDate.getMonth()+1;
var yyyy = currentDate.getFullYear();
var today = yyyy+'-'+mm+'-'+dd;
Posts.find({submitted: today}).count()
However, the last part is returning 0.
Is it because the last hh,mm,ss part of today is missing? If so, how can I tell meteor-mongoto ignore the time part of date so that I can return that count?
I don't like to deal with JS date objects formats, and i guess you either (I do not understand the last part (what format it is))
Give a try to momentjs package, the documentation its pretty clear.
So on the insert you can have something like.
var today = moment().format(''MMMM Do YYYY, h:mm:ss a'); // April 3rd 2015, 12:17:06 pm
Posts.insert({subbmited:today})
and do a simple find like this.
var endQuery = today..add('days', 3).calendar(); // just an example.
Posts.find({submitted: {$gt: today,$lt:endQuery}})
Here thanks to #Larry Maccherone point we are using $gte (grater than) and $lt (less than), so this works like find me post between the post submitted day and the post submitted dat + 3 days (like you ask managing ranges)
You are storing your submitted date in MongoDB with both time and timezone information. Performing a direct comparison of your currentDate with the submitted date in Mongo will never be true, since your currentDate does not contain time information.
Also you are using a String data type to query the date, which also will not work since you need to use a Date data type. Something like this will work for you:
var today = new Date();
today.setHours(0, 0, 0, 0);
Posts.find({submitted: {$gt: today}})
Which will return all the posts with a date greater than midnight of today's date.
Try something like this
posts.find({"submitted": /.*today*/})

Angularjs, Datepicker one day beind

I understand that the datepicker (I'm using AngularStrap's datepicker) is "behind" a day because of how dates are calculated in javascript. My problem is, how to I get it to not take the timezone into consideration and just stick with the entered date... no adjustments?
I select February 1, 2014 in the datepicker. My value on the screen is 2/1/2014 and I want that value to be saved. However, the datepicker turns this into Fri Jan 31 2014 19:00:00 GMT-0500 (EST) apparently because it subtracts the 5 hours for my timezone from the entered date. I do not want this. If I enter 2/1/2014 I want that date, regardless of the timezone.
What is the best way to intercept/change/edit this value so that entering 2/1/2014 gives me exactly that date... no conversion for timezone? Should I modify the datepicker code itself (this seems like a bad idea)? Should I change the value myself prior to sending it to the backend by adding in some sort of offset? If so, how do you add time to a value that console displays as Fri Jan 31 2014 19:00:00 GMT-0500 (EST)?
I solved this problem with a custom directive https://gist.github.com/weberste/354a3f0a9ea58e0ea0de
It's for Angular Bootstrap datepicker but I guess it should work for AngularStrap datepicker as well since it only depends on the corresponding ngModel rather than the datepicker itself.
Essentially, I'm reformatting the value whenever a date is selected on the datepicker (this value, a yyyy-mm-dd formatted string, will be stored on the model) and whenever the model is accessed to populate the view, I need to wrap it in a Date object again so datepicker handles it properly.
In other words, it is exactly doing the interceptions that you ask for in your question.
I know this thread is kind of old but since there is no accepted solution I thought I'd offer what finally worked for me after lots of messing around:
The issue in my case was that the datepicker was using the wrong timezone so when I would try to edit an event, the wrong date would display even though the correct date was stored in the db. The following fixed it for me:
var evDate = new Date(data.eventDate); //data.eventDate is the date string
evDate.setMinutes(evDate.getMinutes() + evDate.getTimezoneOffset());
$scope.eventInfo.eventDate = evDate;
I found this solution here: https://github.com/angular-ui/bootstrap/issues/2628
If you don't mind loading another resource, then I would recommend using MomentJS as it takes the pain out of dates in JavaScript. You can do something like `moment(datepicker value).local()' to get the date without the timezone offset.
http://momentjs.com/docs/#/manipulating/local/
I have found a way. convert that date to string first. here is the code.
var SelectDate = $scope.GetFormattedDate(Date.parse($("#Date").datepicker("getDate")));
$scope.GetFormattedDate = function (CalDate) {
var re = /-?\d+/;
var WDate = CalDate.toString();
var m = re.exec(WDate);
var lastDate = new Date(parseInt(m[0]));
var mm = lastDate.getMonth() + 1;
var dd = lastDate.getDate();
var yyyy = lastDate.getFullYear();
var formattedDate = mm + '/' + dd + '/' + yyyy;
return formattedDate;
}
Now Pass SelectDate to your controller. bingo problem has been resolved :)
Guys if you are experiencing this problem is because probably,you are reactivily ,puting data in boostrap datepicker.This solution worked for me.
First you check if date is null
dateBegin===null?dateBegin=null:dateBegin = new Date(formatDate(dateBegin,'yyyy-MM-dd','en'));
**if is null you set its value to null which you are going putt in your Form Group and in Form Group Control
this.ugovorForm = new FormGroup({'dateBegin':new FormControl(dateBegin)})
else you will set Date and format it using formatDate property , provided by Angular.I was struguling with this problem for along time.And its because I'm loading dates from Database.Good Luck;

how to compare date which is given by user to date in javascript..?

In my web-site I am getting a date from user which in format like "dd-mm-yyyy",now I want to get the date which is 7-day before of that user's date.
I am able to get the current date in format "dd-mm-yyyy" but how would I know the date which is one week before user's date in javascript?
If you already have a Date object, use yourDate.setDate(yourDate.getDate() - 7 );
Try this--
var MyDate = new Date('11/30/2012'); //date format in mm/dd/yyyy
MyDate.setDate(MyDate.getDate() -7)
var newDate = MyDate.getMonth()+1 + '/' + MyDate.getDate() + '/' + MyDate.getFullYear()
alert(newDate);
Note- subtracting seven days to a date shifts the month or year and the changes are handled automatically by the Date object.
Why don't you use datejs, it's the best date related js library I have seen. Chcek the documentation here.
http://code.google.com/p/datejs/wiki/APIDocumentation
Search for add method
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 7 days in past:
var myDate=new Date(); //or users date
// myDate will be users current date
myDate.setDate(myDate.getDate()-7);
//now substract 7 days to get the date u want.
Follow the following link
http://www.w3schools.com/js/js_obj_date.asp
Or follow this
http://www.techrepublic.com/article/manipulate-time-and-date-values-with-javascripts-date-object/6076869
You can convert a date string in the format dd-mm-yyyy to a date object using:
function toDate(d) {
d = d.split('-');
return new Date(d[2], --d[1], d[0]);
}
Then use Osiris' answer to add or subtract 7 days.

Categories