get tomorrows date with jquery and compare - javascript

how is it possble to get the date in this format ? 28/09/2013
what i am getting now is,
Fri Sep 27 2013 15:19:01 GMT+0530 (Sri Lanka Standard Time)
This is the code i have written to get that..
var date = new Date();
var tomorrow = new Date(date.getTime() + 24 * 60 * 60 * 1000);
alert(tomorrow);
and i need to see weather, is the given date is tomorrow. something like this when i give 28/09/2013 it should alert as tomorrow or not.
any help is highlight appreciated.
NOTE : i only need to compare with date. 28/09/2013 === tomorrow

You can try following to get the next day :
var myDate=new Date();
myDate.setDate(myDate.getDate()+1);
// format a date
var dt = myDate.getDate() + '/' + ("0" + (myDate.getMonth() + 1)).slice(-2) + '/' + myDate.getFullYear();
console.log(dt);
Here is the demo : http://jsfiddle.net/5Yj3V/3/

Moment.js will do that for you very easily.
moment().add('days', 1).format('L');

I would use the DateJS library.
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy");

Try the below fiddle using javascript.
var tomorrow = new Date();
var newdate = new Date();
var month = (newdate.getMonth()+1);
newdate.setDate(tomorrow.getDate() + 1);
if (month < 10)
{
month = '0' + (newdate.getMonth()+1);
}
alert(newdate);
alert(newdate.getDate() + '/' + month + '/' + newdate.getFullYear());

Related

Javascript + 7 days ( Only want dd-mm-yy)

I want to change this date to be formatted to DD-MM-YY
new Date(new Date().setDate(new Date().getDate() + 7)))
Current result: Thu Sep 15 2022 02:16:38 GMT+0200 (Central European Summer Time)
Wanted result: 15-09-22
I suggest solving the problem step by step.
Check the Date object documentation. There are methods that return the day, month, and year.
Add leading "0" when you need it. For instance, like this: ${value < 10 ? '0' : ''}${value}.
Concatenate the strings:
`${dayString}-${monthString}-${date.getFullYear()}`
let date = new Date()
date.setDate(date.getDate() + 7);
const day = date.getDate();
const month = date.getMonth();
const dayString = `${day < 10 ? '0' : ''}${day}`;
const monthString = `${month < 10 ? '0' : ''}${month}`;
const formatted = `${dayString}-${monthString}-${date.getFullYear()}`;
const event = new Date(new Date().setDate(new Date().getDate() + 7));
var day = event.getDate();
var month = event.getMonth();
var year = event.getFullYear();
var date = day + '-' + month + '-' + year;
date.toString();
I did find a fix for my issues no more comments are necessary

How do I get a date in YYYY-MM-DD format?

Normally if I wanted to get the date I could just do something like
var d = new Date();
console.log(d);
The problem with doing that, is when I run that code, it returns:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:
8/24/2015
Or, maybe MM-DD-YYYY H:M
8/24/2016 4:20
Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.
var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>
Please note that the timezone of the formatted string is UTC rather than local time.
The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Yet another way:
var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
By using Moment.js library, you can do:
var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
var today = new Date();
function formatDate(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
//return dd + '/' + mm + '/' + yyyy;
return yyyy + '/' + mm + '/' +dd ;
}
console.log(formatDate(today));
function formatdate(userDate){
var omar= new Date(userDate);
y = omar.getFullYear().toString();
m = omar.getMonth().toString();
d = omar.getDate().toString();
omar=y+m+d;
return omar;
}
console.log(formatDate("12/31/2014"));
What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:
var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM
There is really no need to reinvent the wheel.
If you are trying to get the 'local-ISO' date string. Try the code below.
function (date) {
return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}
+date Get milliseconds from a date.
Ref: Date.prototype.getTimezoneOffset
Have fun with it :)
Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.
function returnYYYYMMDD(numFromToday = 0){
let d = new Date();
d.setDate(d.getDate() + numFromToday);
const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
return `${d.getFullYear()}-${month}-${day}`;
}
console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow
Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.
If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.
date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8
Disclaimer: I developed Date-Mirror.
This will convert a unix timestamp to local date (+ time)
function UnixTimeToLocalDate = function( unix_epoch_time )
{
var date,
str;
date = new Date( unix_epoch_time * 1000 );
str = date.getFullYear() + '-' +
(date.getMonth() + 1 + '').padStart( 2, '0' ) + '-' +
(date.getDate() + '').padStart( 2, '0' );
// If you need hh:mm:ss too then
str += ' ' +
(date.getHours() + '').padStart( 2, '0' ) + ':' +
(date.getMinutes() + '').padStart( 2, '0' ) + ':' +
(date.getSeconds() + '').padStart( 2, '0' );
return str;
}
If you want a text format that's good for sorting use:
function formatDateYYYYMMDDHHMMSS(date){
// YYYY-MM-DD HH:MM:SS
const datePart = date.toISOString().split("T")[0]
const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
return datePart + timePart
}
As prototype:
Date.prototype.toSortString = function(){
const date = new Date(this.valueOf());
return date.toISOString().split("T")[0] +
date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01'
new Date().toLocaleDateString("fr-CA",
{year:"numeric", month: "2-digit", day:"2-digit"}
)
const padTo2Digits = num => {
return num.toString().padStart(2, '0')
}
const formatDate = date => {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate())
].join('-')
}
let value = formatDate(new Date())
document.getElementById('dayFormatUS').innerHTML = value
const transformDate = date => {
const convert = date.split('-').reverse()
return convert.join('/')
}
document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
Format US -
<span id='dayFormatUS'></span>
</div>
<div>
Format BR -
<span id='dayFormatBR'></span>
</div>

Date and time in javascript

How can I get the date and time in javascript as 12/08/2015-1:49? I tried the following but I get an error TypeError: now.format is not a function
var now = new Date();
now.format("dd/mm/yy-h:mm tt");
console.log(now); //TypeError: now.format is not a function
There is no any format method for Date in JavaScript. Either you need to use any other external libraries like momentjs, or write your own script to format.
Here is example how you can convert date to dd/mm/yy-h:mm tt format
var now = new Date();
var date = now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear() + "-" + now.getHours() + ":" + now.getMinutes() + " " + (now.getHours() > 12 ? "PM" : "AM");
console.log(date)
Try this:
function getFormattedDate() {
var date = new Date();
var str = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getYear() + "-" + date.getHours() + ":" + date.getMinutes() + " " + date.getSeconds();
return str;
}
Extend Date`s prototype, add function format
Date.prototype.format = function(format){
format = format || "Y/M/D H:I:S";
var data = {
y: this.getFullYear() % 100,
Y: this.getFullYear(),
m: this.getMonth() + 1,
d: this.getDate(),
h: this.getHours(),
i: this.getMinutes(),
s: this.getSeconds()
};
var needAddZeroLTTen = "mdhis".split('');
for(var i = 0; i < needAddZeroLTTen.length; i ++){
var prop = needAddZeroLTTen[i];
data[prop.toUpperCase()] = data[prop] < 10 ? ('0' + data[prop]) : data[prop];
}
var dateStr = format;
for(var i in data){
var reg = new RegExp(i,'g');
dateStr = dateStr.replace(reg, data[i]);
}
return dateStr;
}
Then use below code to format a date
var date = new Date();
var dateStr = date.format('D/M/y-h:I');
the best way to manage dates in js is using http://momentjs.com/ here you will find a great way to format the dates
You can either
do this by hand by using the functions on Date like date.getMonth(), however these do not support zero padding, and it gets quite fiddly. Only do this if you cannot include a third-party library, you're obsessive about load time / performance or you really enjoy re-inventing the wheel.
Use a third-party library like moment, this has multiple formats and supports padding, e.g. MM will force month as two characters.
Example
var now = new Date();
console.log(moment(now).format("DD/MM/YY-hh:mm Z"));
Moment.JS would help you.
Please take a look on this JSFiddle: http://jsfiddle.net/f3zp5zuv/
alert (moment('2015 Apr 30').format('DD/MM/YY -h:mm'))
Moment: http://momentjs.com/docs/#/displaying/
alert (moment('2015 Apr 30 14:42:00').format('DD/MM/YY -h:mm'))
<script src="http://momentjs.com/downloads/moment.js"></script>

How can I format a json date in dd/mm/yy format in javascript?

I have a json date like \/Date(1334514600000)\/ in my response and when I convert it in javascript then I got this date Tue Apr 17 2012 11:37:10 GMT+0530 (India Standard Time),
but I need the date format like 17/04/2012 and I fail every time. Can anyone tell me how can I resolve it?
I don't think that the other posted answers are quite right, you have already accepted one as working for you so I won't edit it.
Here is an updated version of your accepted answer.
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString ));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
alert(date);
It uses a technique from this answer to extract the epoch from the JSON date.
I found very helpful the row1 answer, however i got stuck on the format for input type="date" as only returns one string for decimals under 10, I was able to modify to work on input type="date", I basically adapted the code from row1 to the code from the link http://venkatbaggu.com/convert-json-date-to-date-format-in-jquery/
I was able through jquery .val add the date to the input
var dateString = "\/Date(1334514600000)\/".substr(6);
var currentTime = new Date(parseInt(dateString));
var month = ("0" + (currentTime.getMonth() + 1)).slice(-2);
var day = ("0" + currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = year + '-' + month + '-' + day;
alert(date);
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);
It's answer to your question...
Build the date object with your timestamp
var currentTime = new Date(1334514600000)
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = day + "/" + month + "/" + year
alert(date);​
it works
http://jsfiddle.net/ChgUa/
//parse JSON formatted date to javascript date object
var bdate = new Date(parseInt(emp.Birthdate.substr(6)));
//format display date (e.g. 04/10/2012)
var displayDate = $.datepicker.formatDate("mm/dd/yy", bdate);
Easiest way of formatting date is by using pipes if you are using Angular.
Click here
//in .ts file
ngOnInit() {
this.currentDate = new Date()
}
//in html file
<p>Current date is:</p>{{currentDate | date: 'dd/MM/yyyy'}}
//Output: 22/04/2020
Here is an updated version of your accepted answer. DD/MM/YYYY Format Get Try This..
var dateString = "/Date(1623781800000+0530)/"+.substr(6);
var currentTime = new Date(parseInt(dateString));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if (month.toString().length == 1)
month = "0" + month.toString();
if (day.toString().length == 1){
day = "0" + currentTime.getDate();}
var datenew = day + "/" + month + "/" + year;
var Date = new Date(Tue Jun 15 2021 23:52:47 GMT+0800 (Malaysia Time)).toDateString(); console.log(Date);
Result == Tue Jun 15 2021

Add days to date using Javascript

I am trying to add days to a given date using Javascript. I have the following code:
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var joindate = new Date(datepicker);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.
Fiddle is # http://jsfiddle.net/tassadaque/rEe4v/
Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:
var dmy = "24/06/2011".split("/"); // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
alert(joindate); // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time)
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate); // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
("0" + joindate.getDate()).slice(-2) + "/" +
("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
joindate.getFullYear()
);
Demo here
I would like to encourage you to use DateJS library. It is really awesome!
function onChange(e) {
var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
var new_date = date.add(n).days();
$('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
Assuming numberOfDaysToAdd is a number:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
The first alert is the value of the field. the second is the generated date from a non-US formatted date.
Here is a working example (seems that this kind of markup is necessary to get noticed)
If you want to keep your code, then you need to change
var joindate = new Date(datepicker);
to
var parms = datepicker.split("/");
then use
var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);
OR the identically working
var joindate = new Date(parms[2],parms[1]-1,parms[0]);
As pointed out in a few other answers too, use the .getDate()
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
Lastly you want to add a 0 if the month is < 10
if (mm<10) mm="0"+mm;
If you are using the datepicker from jQuery UI, then you can do
$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());
instead of your function
http://jqueryui.com/demos/datepicker/#method-setDate
Sets the current date for the
datepicker. The new date may be a Date
object or a string in the current date
format (e.g. '01/26/2009'), a number
of days from today (e.g. +7) or a
string of values and periods ('y' for
years, 'm' for months, 'w' for weeks,
'd' for days, e.g. '+1m +7d'), or null
to clear the selected date.
Try
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var parts = datepicker.split(/[^\d]/);
var joindate = new Date();
joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.
To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.
Instead of .val(), use:
var joindate = $('#DatePicker').datepicker("getDate");
to get the underyling Date() object representing the selected date directly from jQuery.
This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.
Then use:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
to move it on.
Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?
I tried this code, it seems ok to me
var joindate = new Date(2010, 5, 24);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
alert(joinFormattedDate);
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);
function onChange(e) {
var datepicker = $("#DatePicker").val().split("/");
var joindate = new Date();
var numberOfDaysToAdd = 1;
joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
$('.new').val(joindate);
}
http://jsfiddle.net/roberkules/k4GM5/
try this.
Date.prototype.addDay = function(numberOfDaysToAdd){
this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};
function onChange(e) {
var date = new Date(Date.parse($("#DatePicker").val()));
date.addDay(1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}

Categories