Format date with "/" to "-" with javascript [duplicate] - javascript

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 7 years ago.
I have this Javascript function that takes X number of days and returns a date in the past
var GetDateInThePastFromDays = function (days) {
var today = new Date();
_date = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days);
return _date.toLocaleDateString();
}
That works absolutely fine, but it returns the date as 06/01/2016 but I want it returned as 06-01-2016 but I can't seem to find out how to do it correctly.

.toLocaleDateString() returns a string formatted according to the user's locale, meaning the format will match whatever is set on the user's machine. For me, that's 06/01/2016 but for an American it might be 01/06/2016 (because they're weird like that).
You should define your own format if you want a fixed one:
function pad(n) {return (n<10 ? "0" : "")+n;}
return pad(_date.getDate()) + "-" + pad(_date.getMonth()+1) + "-" + _date.getFullYear();

Related

Javascript weird date behavior on 2017-03-26. Can't increment one day. Why? [duplicate]

This question already has answers here:
In Javascript "d.setDate(d.getDate() + 1)" gives wrong answer in days when was time change
(1 answer)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
What is going on with the snippet below? I'm trying to build an array of strings as dates starting from a day in the past. I'm able to do it for the whole 2019 year for example. But when I start in 2017-01-01 somehow I CANNOT increment the date past 2017-03-26.
I can increment 2017-03-27 to 2017-03-28 without a problem. Why is this happening?
const currentDay = "2017-01-01";
const nextDay = new Date(new Date(currentDay).setDate(new Date(currentDay).getDate() + 1)).toISOString().split("T")[0];
console.log('currentDay: ' + currentDay);
console.log('nextDay: ' + nextDay);
const currentDay2 = "2017-03-26";
const nextDay2 = new Date(new Date(currentDay2).setDate(new Date(currentDay2).getDate() + 1)).toISOString().split("T")[0];
console.log('currentDay2: ' + currentDay2);
console.log('nextDay2: ' + nextDay2 + '<------ DOES NOT INCREMENT');
const currentDay3 = "2017-03-27";
const nextDay3 = new Date(new Date(currentDay3).setDate(new Date(currentDay3).getDate() + 1)).toISOString().split("T")[0];
console.log('currentDay3: ' + currentDay3);
console.log('nextDay3: ' + nextDay3);
I don't think this is an issue with my environment, but anyway, here's what I'm getting:
Are you guys getting something different?
It is long code to make comment, so decided to make an answer:
const currentDay2 = "2017-03-26";
let [y,M,d] = currentDay2.split(/[-]/);
const nextDay2 = new Date(y, (+M - 1), ++d).toISOString();
console.log(nextDay2);
It looks like Date.Parse() parsed incorrectly.
Since you are working with UTC format dates, and you want to ignore
local timezone changes such as daylight savings time, you should
always use getUTCDate() and setUTCDate(). UTC has no daylight savings.
This is a duplicate of the previous question.
It's working properly on my side.

Javascript date shows a day before [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I'm using mydatepicker in my Angular application. When user clicks a specific date I'm getting the selected date. But I want to have a date format like this.
20180320
or
2018-03-20
So what I did was to convert as follows.
onDateChange(event) {
this.selectDate = event.jsdate.toISOString().slice(0,10)
}
This helps me to get my format. But it shows a day before. That means , if a user selects 2018-03-20 from calendar my selectDate = 2018-03-19
I can do that using moment , but for this project I'm not using for some reasons.Could someone help me to correct this?
Try this to account for timezone
onDateChange(event){
var localDate = new Date(event.jsdate.getTime() - event.jsdate.getTimezoneOffset() * 60000);
this.selectDate = localDate.toISOString().slice(0,10);
}
toISOString is always in UTC+0 time. If you console.log it, you should see a Z on the end. That means GMT.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Just try this with prototype function
Date.prototype.getDDMMYYYY = function () {
var date = JSON.stringify(this.getDate()).length == 1 ? ("0" + this.getDate()) : this.getDate();
var month = JSON.stringify(this.getMonth()).length == 1 ? ("0" + this.getMonth()) : this.getMonth();
var year = this.getFullYear();
return year+"-"+month+"-"+date;
}
and Just replace this code
onDateChange(event){
this.selectDate = event.jsdate.getDDMMYYYY()
}

Date comparison in javascript? [duplicate]

This question already has answers here:
What is the best way to determine if a date is today in JavaScript?
(5 answers)
Closed 7 years ago.
I have some date in milliseconds as 1425133515000 . Now in javascript I need to verify whether 1425133515000 is today or not. Is it possible?
I need one method which takes date in milli seconds and return true if date in milliseconds is today.
New date object from miliseconds:
var dateFromMs = new Date(1425133515000);
And comparsion based on How to know date is today?:
var today = new Date();
if (today.toDateString() === dateFromMs.toDateString()) {
alert('today');
}
You could use the Date constructor taking an Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch) - which is what your integer value represents:
vat date = new Date(1425133515000);
var now = new Date();
Now all that's left is compare is whether the 2 dates represent the same calendar day:
var isSameDay =
date.getDate() === now.getDate() &&
date.getMonth() === now.getMonth() &&
date.getFullYear() === now.getFullYear();

Is there any way to format the date of a field in a query? [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I am getting a query with a field in an undesired date format (Thu Feb 21 00:00:00 EST 2013)
Is there any way to modify this to mm-dd-yyy?
I am using javascript, I found a php way to do it, but sadly it has to be in javascript, so the instruction has to be pretty much the same way it would be in TOAD.
I tried the CONVERT() method and it didn't work. I am not sure I am using it right though
The Convert() function will work, but you need to use the correct format code from here:
SQL Convert() Function.
SELECT Convert(char(10), #date, 110)
Date.js is pretty handy for date formatting.
you probably could try converting to a unix timestamp, then formatting. I havent tested this, and it will probably throw an error, but you get the idea.
var input = your date;
input = input.split(" - ").map(function (date){
return Date.parse(date+"-0500")/1000;
}).join(" - ");
var year = input.getYear();
var month = input.getMonth();
var day = input.getDay();
var hours = input.getHours();
var minutes = input.getMinutes();
var seconds = input.getSeconds();
var formatted = month + " " + day + ", " + year + " at " hours + ':' + minutes + ':' + seconds;
There are basic Date object functions in JS that you can use.
First, create the date variable:
var date = new Date('your date value');
Then you can access the individual date pieces:
var month = date.getMonth() + 1; //gets the month . . . it's 0-based, so add 1
var day = date.getDate(); //gets the day of the month
var year = date.getFullYear(); //gets the 4-digit year
Once you have those values, you can concatenate them in any format that you'd like. For a basic mm-dd-yyyy, use:
var formattedDate = month + "-" + day + "-" + year;
There time and timezone values are also available.
That's a badly mixed up format. There are two basic ways to modify it, one is to just re–order the bits you have, the other is to convert it to a date object and use that to create the new string. Either way, you haven't said what to do with the timezone offset.
Using abbreviations or names for timezones is ambiguous, there is no standard for them and some are duplicted (EST is used for three different timezones). In any case, a simple re–ordering can be:
function formatDate(s) {
var months = {jan:'01', feb:'02', mar:'03', apr:'04',
may:'05', jun:'06', jul:'07', aug:'08',
sep:'09', oct:'10', nov:'11', dec:'12'};
var s = s.split(' ');
var d = (s[2] < 10? '0' : '') + s[2];
return months[s[1].toLowerCase()] + '-' + d + '-' + s[5];
}
alert(formatDate('Thu Feb 21 00:00:00 EST 2013')); // 02-21-2013
The output format (mm-dd-yyyy) is ambiguous, consider using something like 21-Feb-2013 or a standard format like ISO8601 (2013-02-21).
If you need to consider the timezone, it will be easier to create a date object, add the offset, then get back the new date. However, you will also need to work out how to convert the string timezone to a number (preferably minutes, but hours is OK) that can be used with the date.

Format Date in dd.MM.yyyy [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript add leading zeroes to date
It might be a simple question because I am still newbie in JavaScript, assume I have DateTime in ISO format:
2012-07-07T17:00:00
I would like to format this date to string:
07.07.2012
I have written a function to format to 7.7.2012 as below:
var formatDate = function (datum) {
var date = new Date(datum);
return date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();
};
How can I modify this code to get the result 07.07.2012 instead of 7.7.2012
This might be helpful.
<script type="text/javascript">
var date=new Date();
day=date.getDate();
month=date.getMonth();
month=month+1;
if((String(day)).length==1)
day='0'+day;
if((String(month)).length==1)
month='0'+month;
dateT=day+ '.' + month + '.' + date.getFullYear();
//dateT=String(dateT);
alert(dateT);
</script>
You can also take a look at this
Moment.js
Its the best I found, and it also has a host of other useful functions.
use this handy script. The link provides instructions
http://blog.stevenlevithan.com/archives/date-time-format

Categories