Formatting the Date in JavaScript - javascript

Using newDate() function in Java script, I am able to get today's date. I am getting the date in the format 3/3/2009 (d/m/yyyy). But i actually need the date in the format 2009-03-03 (yyyy-mm-dd). Can anyone pls let me know how to format the date as i require?

You usually have to write your own function to handle the formatting of the date as javascript doesn't include nice methods to format dates in user defined ways. You can find some nice pieces of code on the net as this has been done to death, try this:
http://blog.stevenlevithan.com/archives/date-time-format
Edit: The above code seems to be really nice, and installs a cool 'format' method via the date object's prototype. I would use that one.

If you want to roll-your-own, which is not too difficult, you can use the built-in javascript Date Object methods.
For example, to get the current date in the format you want, you could do:
var myDate = new Date();
var dateStr = myDate.getFullYear +
'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
You may need to zero-pad the getDate() method if you require the two-digit format on the day.
I create a few useful js functions for date conversions and use those in my applications.

There's a very nice library to manage date in JS.
Try this.

You'll pretty much have to format it yourself, yeah.
var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
var date = curDate.getDate();
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
var dateString = year + "-" + month + "-" + date;
It's a bit long, but it'll work (:

add jquery ui plugin in your page.
function DateFormate(dateFormate, dateTime) {
return $.datepicker.formatDate(dateFormate, dateTime);
};

Just another option, which I wrote:
DP_DateExtensions Library
Not sure if it'll help, but I've found it useful in several projects.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

Related

Getting today's date from a specific date format in React

I would like to get today's date with the format below in React:
"2019020420"
I am able to get the current date with this function. How do I modify this such that it will give me the above date format?
getCurrentDate() {
var tempDate = new Date();
var date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds();
const currDate = date;
return currDate;
}
You can use template literals.
let formatTwoDigits = (digit) => ("0" + digit).slice(-2);
var tempDate = new Date();
var date = `${tempDate.getFullYear()}${formatTwoDigits(tempDate.getMonth()+1)}${formatTwoDigits(tempDate.getDate())}${formatTwoDigits(tempDate.getHours())}${formatTwoDigits(tempDate.getMinutes())}${formatTwoDigits(tempDate.getSeconds())}`;
console.log(date);
However, implementing date formatting by ourselves sometimes could be tedious. If you don't mind using a library, you can take a look at moment.js and its format functions. Moment.js is a commonly used JS library for parsing, manipulating, and formatting dates.
try this library for formatting date in your desired format.
https://date-fns.org/
use moment.js from https://momentjs.com/
Take a look at there first few examples for how to use it for reformatting dates.

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

No format support in Date object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07

Format date in Javascript [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 have a function which accepts a UTC date. I want to return back the local date.
I have the following code so far:
var dateFormat = function (date) {
var dt = new Date(date + " UTC");
return dt.toString();
}
For the return date, I like it formatted as such:
October 9th, 2013, 7:34:00 PM
Is there a formatting that will handle this.
I usually use moment.js for this kind of tasks. It's pretty powerful and still small sized library. Give it a try.
You have a lot of ways to format the Date object in JavaScript. I suggest you to check out 10 ways to format time and date using JavaScript and Working with Dates. These are the main functions you need to use for formatting JavaScript Dates:
getDate(): Returns the date
getMonth(): Returns the month (Starting from 0)
getFullYear(): Returns the year
A simple script would be:
<script type="text/javascript">
var d = new Date();
var curDate = d.getDate();
var curMonth = d.getMonth() + 1; // Months are zero based
var curYear = d.getFullYear();
document.write(curDate + "-" + curMonth + "-" + curYear);
</script>
In your case, you can have an array of months:
var months = ["January", "February", ... "December"];
The next part would be associating the correct variables with the place they need to be present.
Plugins
But instead of doing all these, you can also consider using a fancy date formatter plugin, that uses jQuery or some library. A few ones would be:
Moment.js is a javascript date library for parsing, validating, manipulating, and formatting dates.
XDate is a thin wrapper around JavaScript's native Date object that provides enhanced functionality for parsing, formatting, and manipulating dates. It implements the same methods as the native Date, so it should seem very familiar.
DateJS is an open source JavaScript Date library for parsing, formatting and processing.

Getting next day date for specific string format in Google Apps Script (JavaScript)

Good day everyone!
Working on aprojectmI had to start working with Google Spereadsheet interface and faced a problem I cannot quickly overcome due to not working with JavaScripts ever before.
I have a date in specific format as a string
var date = "2012-08-09";
What I need is to get the next day date as
date = "2012-08-10";
which should include changing not only the day, but month and year too, if necessary.
I've tried using date format
var datum= new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.toString('yyyy-MM-dd');
but the code appears to fail at writing date to datum variable.
What is the best and quickiest way tosolve this litle problem?
Thanks
The problem when you tag a question 'Javascript' and when you are actually using Google Apps Script is that you get nice answers from people that do not know some special functions available in GAS.
GAS is based on Javascript but Javascript is not GAS... if you see what I mean ;-)
That said, there is actually a "special" function to format date string and I'll show it in the following code.
But there is also another point that could put you into trouble : if you don't mention hours in your date object there is a risk to shift one day if you live in a country that uses daylight savings. This issue has been discussed quite often on this forum and elsewhere so I won't give all the details but it's a good idea to take this into account when you play with date objects. In the code below I extract a tz (time zone) string from the date object we have just created to know if it's in summer or in winter time, then I use this tz string as a parameter in the Utilities.formatDate() method . This guarantees an exact result in every situations.
Here is (finally) the test code :
(use the logger to see results. script editor>view>logs)
function test(){
date = "2012-08-9";
var parts = date.split('-')
var datum = new Date(parts[0],parts[1]-1,parts[2],0,0,0,0);// set hours, min, sec & milliSec to 0
var tz = new Date(datum).toString().substr(25,8);// get the tz string
Logger.log(datum+' in TimeZone '+tz)
datum.setDate(datum.getDate() + 1);// add 1 day
var dateString = Utilities.formatDate(datum,tz,'yyyy-MMM-dd');// show result like you want, see doc for details
Logger.log(dateString);// the day after !
}
Logger results :
Thu Aug 09 2012 00:00:00 GMT+0200 (CEST) in TimeZone GMT+0200
2012-Aug-10
It sounds like a parsing problem you may have better luck, splitting out the date and putting the parameters in individually, any errors you get would be useful:-
var parts = date.split("-");
var datum = new Date(
parseInt(parts[0], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[2], 10));
There is no built in formatting function for the JavaScript Date object, I'm not sure if the google apps api is any different though. To perform the last line of your code you may either need to write your own functions to extract the data from the JavaScript date object and format it, hint you will also need to write a zerofill function if you want to ensure two digits in your date and month parts of the output.
var formatted = datum.getFullYear() + "-" +
zerofill(datum.getMonth() + 1, 2) + "-" +
zerofill(datum.getDate(), 2);
Passing a format string to toString works in .NET, and it may work in Java, however this doesn't work in Javascript.
Try the following,
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
Try the following in http://jsfiddle.net/ It works.....
<html>
<head>
<script>
function foo(){
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
document.getElementById("demo").innerHTML = date;
}
</script>
</head>
<body onload="foo()">
<p id=demo></p>
</body>
</html>​

Categories

Resources