Date Convert in jquery - javascript

I need DD-MM-YYYY Format of the given date.
var todaydate = /Date(1394908200000)/; //Serialize date
var date = eval("new " + todaydate.replace(/\//g, ""));
alert('date is :'+date)
but output look like,
date is :Wed Jun 11 2014 00:00:00 GMT+0530 (India Standard Time)
Expected output like,
date is :11-06-2014

Try this
var date = new Date(); //new Date(1394908200000)
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [day, mnth, date.getFullYear()].join("-");
}
var final = convert(date);
alert('date is :' + final)
DEMO

Besides of JS like other people mention, you can also use the .datepicker from jquery ui plug-in
var dt = $.datepicker.formatDate('dd-mm-yy', new Date(1394908200000));
alert(dt);
JSFiddle, use jquery ui plug-in

WORKING FIDDLE
Try this-
var date = new Date();
function myDateFormatter (dateobject) {
var d = new Date(dateobject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = day + "-" + month + "-" + year;
return date;
};
var dateformat = myDateFormatter(date);
alert('date is :' + dateformat);

Related

add getTime from date to another date without time javascript

I need to add getTime from giving the date to another date format yyyy-mm-dd using javascript.
this is my date :
var m = new Date(res[i].DATESTART).getTime();
add m to another date.
var ddm = formatDate(monday);
var dddm = ddm+" 23:59:59";
var newdate = new Date(dddm);
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}

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>

In Javascript how can i get todays date in this format yyyymmdd

Like i need to get todays date in format like 20120924 (yyyymmdd).How can i get this in javascript.
You could add a method to the date prototype, so you can use it on any date object:
Date.prototype.toMyString = function () {
function padZero(obj) {
obj = obj + '';
if (obj.length == 1)
obj = "0" + obj
return obj;
}
var output = "";
output += this.getFullYear();
output += padZero(this.getMonth()+1);
output += padZero(this.getDate());
return output;
}
var d = new Date();
alert(d.toMyString()); // Today
var otherDate = new Date(2012,0,1);
alert(otherDate.toMyString());​ //Jan 1 2012
Fiddle: http://jsfiddle.net/johnkoer/4rk7K/10/
This worked for me.
var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
Try this.
​var date = new Date();
var year = date.getFullYear().toString();
var month = date.getMonth().toString();
var day = date.getDate().toString();
if (parseInt(month) < 10) month = "0" + month;
if (parseInt(day) < 10) day = "0" + day;
var parsedDate = year + month + day;
(edit)
Improved this function by making the day equate to the day of the month, rather than the day of the week.
How about
date = new Date().toJSON().substr(0,10).split("-")
date = date[0] + date[1] + date[2]
Edit:
This will return the UTC date, not local date...
For local date, you could use:
date = new Date().toLocaleDateString().split("/"); // "M/D/YYYY"
date[0] = date[0].length == 1 ? "0" + date[0] : date[0];
date[1] = date[1].length == 1 ? "0" + date[1] : date[1];
date = date[2] + date[0] + date[1];
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_year + curr_month + curr_date);
That should give the right date:)

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

How to get current date in jQuery?

I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.
Date() is not part of jQuery, it is one of JavaScript's features.
See the documentation on Date object.
You can do it like that:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
See this jsfiddle for a proof.
The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.
If you have jQuery UI (needed for the datepicker), this would do the trick:
$.datepicker.formatDate('yy/mm/dd', new Date());
jQuery is JavaScript. Use the Javascript Date Object.
var d = new Date();
var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();
Using pure Javascript your can prototype your own YYYYMMDD format;
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding
};
var date = new Date();
console.log( date.yyyymmdd() ); // Assuming you have an open console
In JavaScript you can get the current date and time using the Date object;
var now = new Date();
This will get the local client machine time
Example for jquery LINK
If you are using jQuery DatePicker you can apply it on any textfield like this:
$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());
function GetTodayDate() {
var tdate = new Date();
var dd = tdate.getDate(); //yields day
var MM = tdate.getMonth(); //yields month
var yyyy = tdate.getFullYear(); //yields year
var currentDate= dd + "-" +( MM+1) + "-" + yyyy;
return currentDate;
}
Very handy function to use it, Enjoy. You do not require any javascript framework. it just works in with plain javascript.
I know I am Late But This Is All You Need
var date = (new Date()).toISOString().split('T')[0];
toISOString() use built function of javascript.
cd = (new Date()).toISOString().split('T')[0];
console.log(cd);
alert(cd);
Since the question is tagged as jQuery:
If you are also using jQuery UI you can use $.datepicker.formatDate():
$.datepicker.formatDate('yy/mm/dd', new Date());
See this demo.
Here is method top get current Day, Year or Month
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
See this.
The $.now() method is a shorthand for the number returned by the expression (new Date).getTime().
Moment.js makes it quite easy:
moment().format("YYYY/MM/DD")
this object set zero, when element has only one symbol:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
This object set actual full time, hour and date:
function getActualFullDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return day + ". " + month + ". " + year + " (" + h + ":" + m + ")";
}
function getActualHour() {
var d = new Date();
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return h + ":" + m + ":" + s;
}
function getActualDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
return day + ". " + month + ". " + year;
}
HTML:
<span id='full'>a</span>
<br>
<span id='hour'>b</span>
<br>
<span id='date'>c</span>
JQUERY VIEW:
$(document).ready(function(){
$("#full").html(getActualFullDate());
$("#hour").html(getActualHour());
$("#date").html(getActualDate());
});
EXAMPLE
//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19
You can achieve this with moment.js as well.
Include moment.js in your html.
<script src="moment.js"></script>
And use below code in script file to get formatted date.
moment(new Date(),"YYYY-MM-DD").utcOffset(0, true).format();
FYI - getDay() will give you the day of the week... ie: if today is Thursday, it will return the number 4 (being the 4th day of the week).
To get a proper day of the month, use getDate().
My example below... (also a string padding function to give a leading 0 on single time elements. (eg: 10:4:34 => 10:04:35)
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var currentdate = new Date();
var datetime = currentdate.getDate()
+ "/" + strpad00((currentdate.getMonth()+1))
+ "/" + currentdate.getFullYear()
+ " # "
+ currentdate.getHours() + ":"
+ strpad00(currentdate.getMinutes()) + ":"
+ strpad00(currentdate.getSeconds());
Example output: 31/12/2013 # 10:07:49If using getDay(), the output would be 4/12/2013 # 10:07:49
This will give you current date string
var today = new Date().toISOString().split('T')[0];
Try this....
var d = new Date();
alert(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());
getMonth() return month 0 to 11 so we would like to add 1 for accurate month
Reference by : https://www.w3schools.com/jsref/jsref_obj_date.asp
you can use this code:
var nowDate = new Date();
var nowDay = ((nowDate.getDate().toString().length) == 1) ? '0'+(nowDate.getDate()) : (nowDate.getDate());
var nowMonth = ((nowDate.getMonth().toString().length) == 1) ? '0'+(nowDate.getMonth()+1) : (nowDate.getMonth()+1);
var nowYear = nowDate.getFullYear();
var formatDate = nowDay + "." + nowMonth + "." + nowYear;
you can find a working demo here
var d = new Date();
var today = d.getFullYear() + '/' + ('0'+(d.getMonth()+1)).slice(-2) + '/' + ('0'+d.getDate()).slice(-2);
The jQuery plugin page is down. So manually:
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );
console.log($.datepicker.formatDate('yy/mm/dd', new Date()));
Using the jQuery-ui datepicker, it has a handy date conversion routine built in so you can format dates:
var my_date_string = $.datepicker.formatDate( "yy-mm-dd", new Date() );
Simple.
This is what I came up with using only jQuery. It's just a matter of putting the pieces together.
//Gather date information from local system
var ThisMonth = new Date().getMonth() + 1;
var ThisDay = new Date().getDate();
var ThisYear = new Date().getFullYear();
var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();
//Gather time information from local system
var ThisHour = new Date().getHours();
var ThisMinute = new Date().getMinutes();
var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();
//Concatenate date and time for date-time stamp
var ThisDateTime = ThisDate + " " + ThisTime;
You can do this:
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
OR Something like
var dateObj = new Date();
var month = dateObj.getUTCMonth();
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = month + "/" + day + "/" + year;
alert(newdate);
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getYear();
var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;
alert(today);
I just wanted to share a timestamp prototype I made using Pierre's idea. Not enough points to comment :(
// US common date timestamp
Date.prototype.timestamp = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var h = this.getHours().toString();
var m = this.getMinutes().toString();
var s = this.getSeconds().toString();
return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy + " - " + ((h > 12) ? h-12 : h) + ":" + m + ":" + s;
};
d = new Date();
var timestamp = d.timestamp();
// 10/12/2013 - 2:04:19
Get current Date format dd/mm/yyyy
Here is the code:
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().toString().length) == 1)? '0'+(fullDate.getMonth()+1) : (fullDate.getMonth()+1);
var twoDigitDate = ((fullDate.getDate().toString().length) == 1)? '0'+(fullDate.getDate()) : (fullDate.getDate());
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
alert(currentDate);
function createDate() {
var date = new Date(),
yr = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate(),
todayDate = yr + '-' + month + '-' + day;
console.log("Today date is :" + todayDate);
You can add an extension method to javascript.
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
This one-liner will give you YYYY-MM-DD:
new Date().toISOString().substr(0, 10)
'2022-06-09'

Categories