Format Date in dd.MM.yyyy [duplicate] - javascript

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

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.

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

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();

How to add number of weeks to the current date using JavaScript?

I need to run a check on dates, one being a selected date which I had, the second needs to be the current date + 36 weeks.
I've looked around and every solution I've seen involves GetDate() + days.
new Date().getDate() + 252
This is not working, the date currently is 2014/03/07 so the line above takes 7 and adds 252 which is not correct.
I'm looking for any solution using JavaScript or jQuery.
Thanks in advance.
check jsFiddle
JavaScript Code
var newdate = new Date();
newdate.setDate(newdate.getDate()+252); // 36 week * 7 day = 252
alert(newdate.getFullYear() + "-" + (newdate.getMonth() + 1) + "-" + newdate.getDate()); // alert(newdate);
Did you try the date.setDate() function?
var today = new Date();
today.setDate( today.getDate() + 252 );
Please can someone show me how to make current date = 36 weeks and then parse it into the format 'yyyy-MM-dd'
Everything you need is in other answers, but to make it clear
// Start with a date
var d = new Date();
// Create a new date 36 weeks in the future
var e = new Date(+d + 36*7*24*60*60*1000);
// Convert to ISO 8601 format and get just the date part
alert(e.toISOString().split(/t/i)[0]);
or get the bits and format the string yourself:
function pad(n){return (n<10?'0':'')+n}
alert(e.getFullYear() + '-' + pad(e.getMonth()+1) + '-' + pad(e.getDate()));
Try this:
var now = new Date();
now.setDate(now.getDate()+252);
alert(now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate());
Check in fiddle: http://jsfiddle.net/Uz4VV/
I know you said that you were looking to just use JavaScript and jQuery, but there's a library out there called Moment.js that excels at doing just this.
moment().add('weeks', 36);
It's that easy. Why not give it a go?

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.

Javascript date question about format

I've been struggling with javascript more than an hour and came up with a solution - to ask you for help!
A RSS Feed generates the date of every post in this format 2011-05-18T17:32:43Z. How can I make it look like that 17:32 18.05.2011?
Thank you in advance!
Assuming you've parsed the RSS date into a JS Date object (which can be tricky, since many Date.parse implementations don't accept ISO-8601 dates like that)...
//var d=new Date(/*...*/)
// 17:32 18.05.2011
pad(d.getHours())+':'+d.getMinutes()+' '+
pad(d.getDate())+'.'+pad(d.getMonth()+1)+d.getFullYear();
(getMonth returns 0-11 based month)
... you'd also want some kind of zero buffering for the month (in your example) and possibly day, hour (depending)....
function pad(val,len) {
var s=val.toString();
while (s.length<len) {s='0'+s;}
return s;
}
Optionally from string->string you could use:
function reformat(str) {
var isodt=string.match(/^\s*(\-?\d{4}|[\+\-]\d{5,})(\-)?(\d\d)\2(\d\d)T(\d\d)(:)?(\d\d)?(?:\6(\d\d))?([\.,]\d+)?(Z|[\+\-](?:\d\d):?(?:\d\d)?)\s*$/i);
if (isodt===null) {return '';} // FAILED
return isodt[5]+':'+isodt[7]+' '+isodt[4]+'.'+isodt[3]+'.'+isodt[1];
}
You can create a new Date, get the fragments out of it and concatenate everything:
function parse(date) {
var d = new Date(date)
return d.getHours() + ":" + d.getMinutes()
+ " " + d.getDate() + "." + (d.getMonth()+1)
+ "." + d.getFullYear();
}

Categories