Using alert with object date - javascript

I'm learning JavaScript and I'm trying to figure out object date. Specifically toLocaleDateString method.
I've come across two different basic examples of it. The first one is:
var d = new Date();
var n = d.toLocaleDateString();
alert(d);
And the second one is:
var myDate = new Date();
alert(myDate.toLocaleDateString());
Both work fine, but they give different date formats. First one gives: Mon Jul 16 2018 18:34:00 GMT+0200 (Central European Summer Time), while the second one is just 7/16/2018. And I can't see why? What am I missing here?
Thanks!

small error, in the first example you should be alerting n instead of d
var d = new Date();
var n = d.toLocaleDateString();
alert(n);
d is the date object while n is the date string. you are getting different date formats because you are alerting a date object in the first example and a date string in the second

This is simply because you are not alerting the modified date string (which is n) in the first alert:
var d = new Date();
var n = d.toLocaleDateString();
alert(n);
var myDate = new Date();
alert(myDate.toLocaleDateString());

You're printing the wrong variable in the first block. When you declare a variable with the reserved word var in the second line you're storing there the formatted date that you want to output, so you can just alert(n) or you can avoid declaring the var:
var d = new Date();
d.toLocaleDateString();
alert(d);

Related

Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()

How To Convert String ' dd/mm/yy hh:MM:ss ' to Date in javascript?

I have Done this
var d='dd/mm/yy hh:MM:ss';
var d1=d.split(" ");
var date=d1[0].split("/");
var time=d1[1].split(":");
var dd=date[0];
var mm=date[1]-1;
var yy=date[2];
var hh=time[0];
var min=time[1];
var ss=time[2];
var fromdt= new Date("20"+yy,mm-1,dd,hh,min,ss);
Is there Any way to do it using JQuery OR JavaScript?
If you are looking for alternatives in jquery or Javascript , then you can go with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
This will work regardless of timezone for the format dd/mm/yyy hh:mm:ss only. It also does not rely on third party packages:
let dtStr = "12/03/2010 09:55:35"
console.log(strToDate(dtStr)); // Fri Mar 12 2010 09:55:35
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1], timeParts[2]);
}
How about Date.parse()?
new Date( Date.parse("05/12/05 11:11:11") );
// Thu May 12 2005 11:11:11 GMT+0200 (CEST)
The output produced is in local timezone and will differ in browsers in different timezones.
We can convert any local date format to datetime datatype using moment js.
Syntax:
moment('<local date value>','<local date format>').format('<expected convert format>')
Example:
moment('26/05/1986 00:00', 'DD/MM/YYYY HH:mm').format("MM/DD/YYYY HH:mm");
then the output will be 05/26/1986 00:00
Cheers
Date#parse should be able to parse that if you split on a string. Id also recommend looking into the npm package moment for date manipulation
From your code it seems that you are trying to convert string into date and also you are trying to fetch previous month. If yes then you can reconstruct your code as below:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
return d;
}
$(document).ready(function() {
var dateString='2015-06-17T18:30:12';
var d = new Date(dateString);
alert(d.SubtractMonth(1));
});

Add Number of months to a Date in a text field

function addDays(){
var myDate =document.getElementById('treatdate');
var numberOfDaysToAdd = document.getElementById('resultdays');
var tset = numberOfDaysToAdd.value;
var result1 = myDate.value.addMonths(parseInt(tset));
var pldate= moment(result1).format('YYYY-MM-DD');
return pldate; }
'treatdate' is an id for a treatment date which is pulled from my database. Thanks in advance.
You can always use moment.js library for Date manipulations. http://momentjs.com/
For your problem you can do the following.
function addDays(){
var datefrmDb = $('#treatdate').val();
var monthstoadd= $('#resultdays').val();
var new_date = (moment(datefrmDb, "YYYY-MM-DD").add('months', monthstoadd)).format("YYYY-MM-DD");
return new_date;
}
If your date format is yyyy-MM-dd
var myDate = new Date(document.getElementById('treatdate').value);
this will a date and time.
Example:
var dd = new Date("2014-02-02 11:11:11")
console log
Sun Feb 02 2014 11:11:11 GMT+0000 (GMT Standard Time)
See if this snippet can help you understand how to manipulate dates. To change/add the months to a Date() object you can use the setMonth() method.
numberOfMonthsToAdd = 5; // the number of months that you want to add
date = new Date(); // creating a Date object
date.setMonth(numberOfMonthsToAdd); // adding the number of months
Note that you may add numbers beyond 12 - the object handles the date, and jumps to the next year.

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

JavaScript New Date()

I have the following JavaScript code but for some reason time is not including minutes:
var austDay = $("#<%= hiddenFieldTime.ClientID %>").val().split(" ");
var year = austDay[0];
var months = austDay[1];
var days = austDay[2];
var time = austDay[3];
var timeUntil = new Date(parseInt(year), parseInt(months),
parseInt(days), parseInt(time));
When I debug using firebug these are my value:
$("#ctl00_hiddenFieldTime").val() = "2011, 5, 6, 14:20:00"
year = "2011,"
months = "5,"
days = "6,"
time = "14:20:00"
timeUntil = Date {Mon Jun 06 2011 14:00:00 GMT-0400 (Eastern Daylight Time)}
As you can see, timeUntil is set to 14:00:00 instead of 14:20:00
parseInt(time) is the problem
Here are the few dates initialization format
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
According to the Mozilla documentation for Date, the following constructors are supported:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
This means that in your constructor, when you pass parseInt(time), that parameter is only used for the hour parameter. You need to pass a separate parameter for minutes, and yet another one if you happen to want seconds.
Also, you should always pass a base parameter to parseInt, like so:
parseInt(hours, 10)
Otherwise when you go to parse a value with a leading 0 such as parseInt('08'), the value will be interpreted as an octal number.
Your last conversion is going to drop everything after the colon:
parseInt("14:20:00"); // 14
The whole conversion is rather bloated, I suggest trying to format the string initially in a format you can pass as is to JS's Date constructor, which will make life easier.
parseInt ("14:20:00") returns 14

Categories

Resources