Is there any simple way to convert the following:
2011-08-31T20:01:32.000Z
In to UK date format: 31-08-2011
and time to: 20:01
You can use momentjs (http://momentjs.com/):
var date = moment(dateObject).format("YYYY-MM-DD");
var time = moment(dateObject).format("HH:mm:ss");
You can use jquery-dateFormat plugin. The following should do the trick:
$.format.date('2011-08-31T20:01:32.000Z', "dd-MM-yyyy"));
$.format.date('2011-08-31T20:01:32.000Z', "hh:mm"));
Date:
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var date = currentTime.getDate();
var year = currentTime.getFullYear();
$('#date1').html(date + '-' + month + '-' + year);
Time:
<script type="text/javascript">
var tick;
function stop() {
clearTimeout(tick);
}
function clock() {
var ut=new Date();
var h,m,s;
var time="";
h=ut.getHours();
m=ut.getMinutes();
s=ut.getSeconds();
if(s<=9) s="0"+s;
if(m<=9) m="0"+m;
if(h<=9) h="0"+h;
time+=h+":"+m+":"+s;
document.getElementById('clock').innerHTML=time;
tick=setTimeout("clock()",1000);
}
</script>
<body onload="clock();" onunload="stop();">
<p><span id="clock"></span></p>
</body>
var a = '2011-08-31T20:01:32.000Z';
var b = new Date(a);
See http://www.w3schools.com/jsref/jsref_obj_date.asp for methods you can use on b now.
var rg=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\..*/g;
var dateStr="2011-08-31T20:01:32.000Z".replace(rg,"$3-$2-$1"); // result is 31-08-2011
var timeStr="2011-08-31T20:01:32.000Z".replace(rg,"$4:$5"); // result is 20:01
var date = new Date("2011-08-31T20:01:32.000Z").toLocaleDateString();
// date = 2011/08/31
date = date.split("/");
// date = ["31", "08, "2011"]
date = date[2] + "-" + (date[0].length == 1 ? "0" + date[0] : date[0]) + "-" + (date[1].length == 1 ? "0" + date[1] : date[1]);
// data = 2011-31-08
$("#your-txtbox").val(date);
Use the date object:
d = new Date('2011-08-31T20:01:32.000Z');
date = d.format("dd-mm-yyyy");
time = d.format("HH:MM");
Related
So what I have is a time string which shows the time as h:m:s.ms
But the problem is that I want to covert them to timestamp values it shows NaN values.
I am using Date.parse() to convert the time into timestamp.
Here is the code that I have tried.
var date;
function myFunction() {
var d = new Date();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var maindate = h + ":" + m + ":" + s + "." + ms ;
var datestring = Date.parse(maindate)
var data = Math.random(0,1);
console.log("Date : ", maindate) ;
console.log("Data : ", data);
}
myFunction();
You can see the date and data in the console window.
the date variable here shows NaN Value.
Please tell me what I am doing wrong.
If you want a timestamp you need a full time with day, month and year
var date;
function myFunction() {
var d = new Date();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var day = d.getDate();
var month = d.getMonth() + 1; // getMonth returns an integer between 0 and 11
var year = d.getFullYear();
var maindate = `${day}-${month}-${year} ${h}:${m}:${s}.${ms}`;
var datestring = Date.parse(maindate)
console.log("Data : ", datestring);
}
myFunction();
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
As I want to get the timestamp in result. I got my sholution of the above question that I posted
Here is the Final code which is giving me the expected result.
function addZero(x,n) {
while (x.toString().length < n) {
x = "0" + x;
}
return x;
}
var date;
function myFunction() {
var d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12
var year = d.getFullYear();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var maindate = year +"-" + day + "-" + month +" "+ h + ":" + m + ":" + s + "." + ms ;
var datestring = Date.parse(maindate)
var data = Math.random(0,1);
console.log("Date : ", datestring) ;
console.log("Data : ", data);
}
myFunction();
I had to include the day month and year value also. WHich I updated in the Answer. rest of the code works fine.
For this, you don't need your addZero() function any more and it's unnecessary to delacre var date; globally.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var ms = d.getMilliseconds();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var maindate = day + '-' + month + '-' + year + ' ' + h + ':' + m + ':' + s + '.' + ms;
var datestring = Date.parse(maindate);
console.log("Data : ", datestring);
Take a look at momentjs.com, maybe this could be a clean and simple solution for you too - depending on your environment.
I want to change date format sequence from yy-mm-dd to dd-mm-yy
How can I do it in Javascript ?
I have tried
var now = new Date();
now.format("mm-dd-yy");
But its not working for me
Here is a clear and simple approach
var now = new Date();
var dd = now.getDate(); //returns date
var mm = now.getMonth()+ 1; //returns month and you need to add1 because it is array
var yy = now.getFullYear(); //returns full year
var st = dd + '-' + mm + "-" + yy; //format as string
var dateFormatted = (now.getMonth()+1)+"-"+now.getDate()+"-"+now.getFullYear();
You can use the below mentioned function to format Date
utilities.FormatDate(new Date(),"GMT", "dd/MM/yyyy")
function dateformat(date)
{
var yourdate = new Date(date);
yourdate = yourdate.getDate() + '-' + yourdate.getMonth() +1 + "-" +yourdate.getFullYear();
}
use - or / as you like
I have a string that has a date in it and I wan't to be able to convert it.
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "-" + day + "-" + year;
alert(shortStartDate);
I want it so it converts March-09-2010 to 09-03-10 (DD-MM-YY)
Anyone know what I am doing wrong?
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate.replace(/-/g, "/")); // replace hyphen with slash
var month = convertedStartDate.getMonth() + 1
var date = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = date + "-" + month + "-" + year;
alert(shortStartDate);
demo: http://jsfiddle.net/BjnBW/
Try this:
var dt=Date.parse(Yourstring);
formatDate('DD-MM-YY',dt);
Please check this Date.parse
Check your syntax changed your code a little, modify it according to it then ---
var startDate = "March/09/2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = day+ "-" + month+ "-" + year;
alert(shortStartDate);
your date string is not in the correct format. for correct formats, please see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
try this or jsfiddle
var startDate = "March-09-2010";
var tmp = startDate.split('-');
tmp.splice(1, 0, ',');
var convertedStartDate = new Date(tmp.join(' '));
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = ('0' + day).slice(-2) + "-" + ('0' + month).slice(-2) + "-" + year;
alert(shortStartDate);
var shortStartDate =
Globalize.format(Globalize.parseDate(startDate, 'MMMM-dd-yyyy'), 'dd-MM-yy');
Use some library to do the conversion, because the built-in Date.parse() is implementation-dependent. It depends on the system locale what formats it accepts.
The code above uses Globalize.js, which can handle a large number of date formats, including formats with month names in different languages (the default being English).
You'll need to convert 'March' to a number. One way is to use this Array extension to be able to retrieve a month number from a month name:
Array.prototype.enum = function(){
var obj = {};
for (var i=0; i<this.length; (i+=1)) {
obj[this[i]] = i;
}
this.enum = obj;
return this;
};
Now, create an Array with month names
var months = ('January,February,March,April,May,June,July,'+
'August,September,October,November,December').split(',')
.enum();
Now you rewrite your date:
var startDate = "March-09-2010".split(/\-/),
month = months.enum[startDate[0]]+1;
startDate = [startDate[1],
month < 10 ? '0'+month : month,
startDate[2]].join('-');
//=> startDate now is: '09-03-2010'
Use getDateFromFormat() to convert string to date in javascript.
Check this link for more help: http://www.mattkruse.com/javascript/date/
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'
I have dates and times in a database in the following format:
2011-08-02T00:00:00-00:00
What is the easiest way to convert them to something like 8-2-2011?
Thanks,
var date = "2011-08-02T00:00:00-00:00".split('T')[0].split('-').reverse();
var month = date[0], day = date[1];
//remove 0 in the beginning if not necessary
if (+month < 10) {
month = month.slice(1);
}
if (+day < 10) {
day = day.slice(1);
}
//swap between the two
date[0] = day;
date[1] = month;
date.join('-');
Or you can use the boring Date way.
Here's the code:
x=new Date("2011-08-02T00:00:00-00:00")
str=(x.getUTCMonth()+1)+"-"+x.getUTCDate()+"-"+x.getUTCFullYear()
Or:
x="2011-08-02T00:00:00-00:00"
x=/^(\d+)\-(\d+)\-(\d+)/.exec(x)
if(x){
str=(parseInt(x[2],10)+"-"+parseInt(x[3],10)+"-"+parseInt(x[1],10))
}
This format will work in the Javascript Date constructor:
var d = new Date("2011-08-02T00:00:00-00:00");
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var output = month + "-" + day + "-" + year;
one way could be to split up the date part
var date = "2011-08-02T00:00:00-00:00";
var dpart = (date.substr(0,10)).split("-");
var odate = parseInt(dpart[1],10)+"-"+parseInt(dpart[2],10)+"-"+dpart[0];