Related
I am trying to convert javascript date to c# datetime
JavaScript Code
var date = new Date();
var day = date.getDay();
var month = date.getMonth();
var year = date.getFullYear();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
// After this construct a string with the above results as below
var JSDateString = year+ "-" + month + "-" + day + " " + hour + ':' + minute + ':' + second;
C# Code
var JSDateString = "2016-04-02 17:15:45"; // I receive date string via Ajax call in this format
var dt = DateTime.ParseExact(JSDateString , "yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
I get invalid datetime format exception. I researched other options in internet but I didn't find any specific answer on how to convert JavaScript datetime to C# datetime.
mm is for minutes, you want MM for month:
var dt = DateTime.ParseExact(JSDateString , "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
This might help with the JavaScript side:
function getDate() {
var date = new Date(),
year = date.getFullYear(),
month = (date.getMonth() + 1).toString(),
formatedMonth = (month.length === 1) ? ("0" + month) : month,
day = date.getDate().toString(),
formatedDay = (day.length === 1) ? ("0" + day) : day,
hour = date.getHours().toString(),
formatedHour = (hour.length === 1) ? ("0" + hour) : hour,
minute = date.getMinutes().toString(),
formatedMinute = (minute.length === 1) ? ("0" + minute) : minute,
second = date.getSeconds().toString(),
formatedSecond = (second.length === 1) ? ("0" + second) : second;
return year + "-" + formatedMonth + "-" + formatedDay + " " + formatedHour + ':' + formatedMinute + ':' + formatedSecond;
};
View a fiddle here: https://jsfiddle.net/kpduncan/de8j318k/
I had too do something like this when I building an application due to not being allowed to add thrid party JS and needing support back to IE8.
As you can see on the MSDN, mm is for minutes (00 - 59) whereas MM is for the month (01 - 12).
var JSDateString = "2016-04-02 17:15:45";
var formatCode = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(JSDateString , formatCode, CultureInfo.InvariantCulture);
You can see that mm is for minutes because you already use it in your HH:mm:ss.
function formatDate(dt) {
//var date = new Date(dt);
var date = new Date('2015-08-27 16:00:00'); alert(date.getMonth());
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + date.getMonth() + " " + date.getFullYear() + " " + strTime;
}
I have tried to fetch Date and time. But I am getting NaN while alert date.getMonth();.
If I am removing time then this is working fine. But My date-time format dynamic. This is coming from the database like 0000-00-00 00:00:00.
I want to view my database date and time in the 27 Aug 2015 04:00:00 am/pm format.
The date format you are using (2015-08-27 16:00:00) is not the proper format for Firefox, though it works in Chrome. So, for this code to work properly on all browsers, it should not be used.
The below code works in Firefox and Chrome:
I've replaced the string variable date - with /. This format works for both Firefox and Chrome.
Another format that works in Firefox and Chrome is 1995-12-17T03:24:00 which includes T instead of ' ' (space).
However, the above format gives different value in Chrome and Firefox.
new Date('2015-10-05T03:24:00'); // Returns Mon Oct 05 2015 08:54:00 GMT+0530 (IST) in Chrome
new Date('2015-10-05T03:24:00'); // Returns 2015-10-04T21:54:00.000Z in Firefox
var date1 = '2015-08-20 09:38:20';
var date1Updated = new Date(date1.replace(/-/g,'/'));
alert(date1Updated.getMonth());
var strDate = addZero(d.getDate()) + "/" + addZero((d.getMonth() + 1))+"/" +d.getFullYear();
alert("strDate :"+strDate)
return strDate;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.
Note: January is 0, February is 1, and so on.
you need to add one like getMonth() + 1.
function formatDate(dt) {
//var date = new Date(dt);
var date = new Date('2015-08-27 16:00:00');
//alert(date.getMonth() + 1);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + (date.getMonth() + 1) + " " + date.getFullYear() + " " + strTime;
}
alert(formatDate());
In firefox '2015-08-27 16:00:00' is an invalid date.
Your options are
var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
In your case you're missing the T before the time
Documentation
You have an invalid date format, It seems Chrome handle this situation but firefox not.
new Date('2015-08-27 16:00:00') // Invalid format
new Date('2015-08-27T16:00:00') // Correct Format With T
Your code doesn't work in firefox
In firefox 2015-08-27 16:00:00isn't valid.
To be valid it has to be 2015-08-27T16:00:00.
To make it valid in firefox, the easiest solution would be
function formatDate(dt) {
//var date = new Date(dt);
var sampleDate = "2015-08-27 16:00:00"; // Your sample date as string
var another = sampleDate.replace(' ', 'T');// Change here. Replaced the empty space with the 'T' to make it work in firefox
var date = new Date(another); alert(date.getMonth()); // Using your date to create new Date object
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + date.getMonth() + " " + date.getFullYear() + " " + strTime;
}
Hope i was helpfull
Parsing strings using the Date constructor is largely implementation dependent. Only one format of string is specified as being supported by the specification and that changed to some extent between ES5 and ECMAScript 2015.
Your best option is to manually parse the string, either using your own function or a library. The following will suit if the string is consistently the format in the OP and the timezone is UTC:
/* parse dates of format yyyy-mm-dd hh:mm:ss
** e.g. 2015-08-27 16:00:00
**
** #param {string} s - Date string in format yyyy-mm-dd hh:mm:ss
** #returns {Date} - String as Date assuming UTC
**
** Does not validate that the string is valid date or time
**/
function parseDate (s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
document.write(parseDate('2015-08-27 16:00:00'));
This question already has answers here:
Formatting the date time with Javascript
(12 answers)
Closed 8 years ago.
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
Luxon: [CDN] | [Source] | [Minified]
Moment.js: [CDN] | [Source] | [Minified]
Datejs: [CDN] | [Source] | [Alpha1.zip (1.6MB)]
Demo
Update: I wrote a one-liner using Moment.js Luxon below.
const { DateTime } = luxon;
const value = DateTime
.fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.toFormat('MM/dd/yyyy h:mm a');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>
Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.
const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}
You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
Fiddle
I'm having trouble converting an example string: 'Sun Feb 02 19:12:44 +0000 2014'
to mysql dateTime format in javascript
any help would be greatly appreciated
You can convert date time to mysql format using this code:
var myDate = new Date('Sun Feb 02 19:12:44 +0000 2014'),
year = myDate.getFullYear(),
month = ('0' + (myDate.getMonth() + 1)).slice(-2),
day = ('0' + myDate.getDate()).slice(-2),
hour = ('0' + myDate.getHours()).slice(-2),
minute = ('0' + myDate.getMinutes()).slice(-2),
seconds = ('0' + myDate.getSeconds()).slice(-2),
mysqlDateTime = [year, month, day].join('-') + ' ' + [hour, minute, seconds].join(':');
However I would suggest to send it to backend as timestamp (+(new Date('Sun Feb 02 19:12:44 +0000 2014'))) or formatted string (myDate.toISOString()) and proceed with conversion there.
try this:
var d = new Date('Sun Feb 02 19:12:44 +0000 2014');
var month = d.getMonth();
if(month < 10)
month = "0" + month;
var day = d.getDate();
if(day < 10)
day = "0" + day;
hour = d.getHours();
if(hour < 10)
hour = "0" + hour;
minute = d.getMinutes();
if(minute < 10)
minute = "0" + minute;
seconds = d.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;
var mysqlDate = d.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds;
I have the following test Script to display the current date & time :-
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var days = date.getDay();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = date + ' ' + hours + ':' + minutes + ' ' + ampm;
return strTime;
}
which will display the following :-
Fri Aug 30 2013 16:36:10 GMT+0100 (GMT Standard Time) 4:36 pm
but i need to modify this to display only:-
Fri Aug 30 2013 4:36 pm
can anyone advice on how i can achieve this ?
Demo using Console.Log
// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// log the date in the browser console
console.log('date:', n);
// log the time in the browser console
console.log('time:',time);
Demo using a DIV
// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = n + ' ' + time;
<div id='time'></div>
Note: these functions aren't fully cross browser supported
Cross-Browser Functional
//Fri Aug 30 2013 4:36 pm
console.log(formatAMPM(new Date()));
//using your function (passing in date)
function formatAMPM(date) {
// gets the hours
var hours = date.getHours();
// gets the day
var days = date.getDay();
// gets the month
var minutes = date.getMinutes();
// gets AM/PM
var ampm = hours >= 12 ? 'pm' : 'am';
// converts hours to 12 hour instead of 24 hour
hours = hours % 12;
// converts 0 (midnight) to 12
hours = hours ? hours : 12; // the hour '0' should be '12'
// converts minutes to have leading 0
minutes = minutes < 10 ? '0'+ minutes : minutes;
// the time string
var time = hours + ':' + minutes + ' ' + ampm;
// gets the match for the date string we want
var match = date.toString().match(/\w{3} \w{3} \d{1,2} \d{4}/);
//the result
return match[0] + ' ' + time;
}
Try this:
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
DEMO
Updated to use the more modern Luxon instead of MomentJS.
Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html
From their site:
https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toLocaleString
//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
(function(con) {
var oDate = new Date();
var nHrs = oDate.getHours();
var nMin = oDate.getMinutes();
var nDate = oDate.getDate();
var nMnth = oDate.getMonth();
var nYear = oDate.getFullYear();
con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
con.log(nHrs + ' : ' + nMin);
})(console);
This produces an output like:
30 - 8 - 2013
21 : 30
Perhaps you may refer documentation on Date object at MDN for more information
You can try the below:
function formatAMPM() {
var date = new Date();
var currDate = date.getDate();
var hours = date.getHours();
var dayName = getDayName(date.getDay());
var minutes = date.getMinutes();
var monthName = getMonthName(date.getMonth());
var year = date.getFullYear();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
alert(strTime);
}
function getMonthName(month) {
var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return ar[month];
}
function getDayName(day) {
var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
return ar1[day];
}
EDIT: Refer here for a working demo.
(new Date()).toLocaleString()
Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"
The request was to format a date in this format:
Fri Aug 30 2013 4:36 pm
I strongly suggest that anyone who comes across this question should use JavaScript's Intl API to format your dates instead of trying to come up with your own preferred format.
Here's an example
let d = new Date();
let formatter = Intl.DateTimeFormat(
"default", // a locale name; "default" chooses automatically
{
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric"
}
);
console.log(formatter.format(d));
The output for me, in the en-US locale, is:
Wed, Sep 30, 2020, 5:04 PM
The output for someone in Mexico (es-MX), is:
miƩ., 30 de septiembre de 2020 17:23
Why is Intl better?
It's native code, with no string manipulation, no extra frameworks required, just a browser from any time after 2013 (when this question was first posted)
Nothing to download
No frameworks to add
Native code runs faster
Intl formats dates as appropriate for the user's locale, e.g. a user in a different country who would prefer to read the year before the month would see the appropriately formatted date
Get the data you need and combine it in the String;
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();
Check out : Working With Dates
To return the client side date you can use the following javascript:
var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;
or in jQuery:
var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
$('#date').html(date);
equivalent to following PHP:
<?php date("j.n.Y"); ?>
To get equivalent to the following PHP (i.e. leading 0's):
<?php date("d.m.Y"); ?>
JavaScript:
var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;
if(day < 10){
day = "0"+d.getDate();
}
if(month < 10){
month = "0"+eval(d.getMonth()+1);
}
var date = day+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;
jQuery:
var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;
if(day < 10){
day = "0"+d.getDate();
}
if(month < 10){
month = "0"+eval(d.getMonth()+1);
}
var date = day+"."+month+"."+d.getFullYear();
$('#date').html(date);
<!-- //Hide From Old Browsers
var d=new Date();
var y=d.getYear();
if (y < 1000)
y+=1900;
var day=d.getDay();
var m=d.getMonth();
var daym=d.getDate();
if (daym<10)
daym="0"+daym;
var mon=new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
document.write("<font size='2' color='#660000'>"+mon[m]+" "+daym+", "+y+"</font>");
// End Hide -->
Result : November 08, 2014
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!
var yyyy = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
if(h<10){h='0'+h}
if(m<10){m='0'+m}
if(s<10){s='0'+s}
onload = function(){
$scope.currentTime=+dd+'/'+mm+'/'+yyyy+' '+h+':'+m+':'+s;
}
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
if (h < 10) { h = '0' + h }
if (m < 10) { m = '0' + m }
if (s < 10) { s = '0' + s }
var ctoday = dd + '/' + mm + '/' + yyyy+ '\t' +h+ ':' +m+ ':' +s;
var d = new Date()
var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
console.log("Today is " + weekday[d.getDay()])
document.getElementById('time').innerHTML = '<span style="color:blue">' + weekday[d.getDay()] + ", " + ctoday + '</span>';
</script>
<div>
<span> Today is : <span id="time"> </span>
</div>
function showTime(){
let date = new Date();
let h = date.getHours();
let m = date.getMinutes();
let s = date.getSeconds();
let d = date.getDate() ;
let month = date.getMonth()+1;
let year = date.getFullYear();
let session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
d = (d < 10) ? "0" + d : d;
//Adds zero when less than 10.
month = (month < 10) ? "0" + month : month;