Current time in YouTube date API format - javascript

I am using the YouTube API and it returns uploaded & updated times in this format: 2013-05-13T13:12:42.000Z (ISO 8601). How can I get the relative time using Javascript (or jQuery)?
Some sources that I've tried to combine to get this to work, however they all appear to format the date differently.
Javascript time to relative
Format ISO-8601 into a date object

Use this timeDifference(new Date(), new Date().setTime(Date.parse("2013-05-13T13:12:42.000Z")))
If you have a problem with the "(ISO 8601)" part, use this timeDifference(new Date(), new Date().setTime(Date.parse("2013-05-13T13:12:42.000Z (ISO 8601)".replace(/ *\(.*\)/,""))))

Click here to check the Demo
var MyDate = new Date(
Date.parse
(
"2013-05-13T13:12:42.000Z (ISO 8601)"
.replace(/ *\(.*\)/,"")
)
);
var date_Str = MyDate.getMonth() +
1 +
"/" +
MyDate.getDate() +
"/" +
MyDate.getFullYear();
Add more function
1. MyDate.getHours()
2. MyDate.getMinutes()
3. MyDate.getSeconds()
Result - "5/13/2013"

Related

Combining Date and Time into DateTime with Google Scripts

I'm having a hard time with Date and Time objects in Javascript.
Starting from a CSV file, it contains the values "12/3/2019" and "14:00:00" in two different cells and I'm importing those values with SpreadsheetApp.open() for the CSV-file.
It now seems the Date Object has the desired date, with a wrong time (11:00 instead of 14:00). However, the Date Object for the time (14:00:00) get's wrong:
If time is set to the value "14:00" imported by the SpreadsheetApp.open() command, the following command
new Date ( time )
yields something very weird: 12/31/1969 13:00:00.
Does anyone have any ideas about how to combines both date and time object into something which can then be used by the CreateEvent() command?
Thanks in advance for all help!
If you pass the string to the constructor of the built-in 'Date' object, the parameter must be in the format readable to the Date.parse() method. Therefore, if your plan is to parse dates from strings, construct the resulting string using the following template
2011-10-10T14:48:00
where 'T' is the delimiter. More on the Date object here
Here's the example of building the template string. You could use Utilities.formatDate(date, timezone, format) as a shortcut but this is how you build the template step by step:
var d = new Date();
//Date template
var template = "YYYY-MM-DDTHH:mm:ss";
//Year
template = template.replace("YYYY", d.getFullYear());
//Month. Add leading zero if required.
template = template.replace('MM', ("0" + (d.getMonth() + 1)).slice(-2));
//Date. Add leading zero if required.
template = template.replace('DD', ("0" + d.getDate()).slice(-2));
//Hours
template = template.replace('HH', ("0" + d.getHours()).slice(-2));
//Minutes
template = template.replace('mm', ("0" + d.getMinutes()).slice(-2));
//Seconds
template = template.replace('ss', ("0" + d.getSeconds()).slice(-2));
Logger.log(template);
var anotherDate = new Date(template);

DateTime value passing incorrectly from javascript to C#

I am using the below code to make call to the controller
DateFrom: moment.utc($(".datefrom").val(), "DD/MM/YYYY").toString()
in the ajax call I had a breakpoint and checked what is being passed and the value was
"Wed Jun 20 2018 00:00:00 GMT+0000"
But when I check it in the C#, this is what is getting passed
Other values are getting passed correctly, but this DateFrom has an issue
I checked both the property names and they are exactly the same.
What am I missing?
Always serialize DateTime values using ISO8601 notation. Most libraries, including momentjs, have built in methods for converting a datetime instance to an ISO8601 string and for parsing them from an ISO8601 back to a datetime instance (no additional call needed for momentjs when parsing, the constructor will handle it without additional input).
Keep in mind this is a separate concern from displaying the value on screen. The display and/or edit value should be localized for the user doing the viewing/entry. The serialized value is the value as it is sent between tiers or devices.
This is because javascript use dates as milliseconds since 1970-01-01 and c# 01/01/1900 so in milliseconds there are a big difference.
I suggest you change your string format to dd/MM/yyyy HH:mm:ss.
The best way is converting your date in javascript to a string that c# can recognize.
var date = new Date();
var day = date.getDate(); // yields date
var month = date.getMonth() + 1; // yields month (add one as '.getMonth()' is zero indexed)
var year = date.getFullYear(); // yields year
var hour = date.getHours(); // yields hours
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds
var data= day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second;
After that send the "data" to your controller in C#
DateTime date=DateTime.ParseExact(data, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Change date format to client date format

Using javascript on Ajax call I get the date format as
Mon Feb 13 2017 00:00:00 GMT+0530(India Standard Time).
I want to change the date format according to clients system date format using javascript.
Can anybody help me with this issue...
Edit:
You can use .toLocaleDateString() to format date based on the client's machine.
var date=new Date();
alert(date.toLocaleDateString());
You should really be using moment.js.
you can initialize locale using moment.locale(); and then format it accordingly.
Follow the link for documentation
Use dateObj.getTimezoneOffset() method to get the timezone offset and then add/subtract according to the result you receive, as described here on
MDN and already answered stackoverflow question
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the time based on local time
date.toLocaleString();
as answered by #Adorjan Princz
simple... the following code should do the job :
var date = new Date();
var dateString = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
console.log(dateString);
hope this helps :)

Create program to display current date and time

Help! I'm new to Javascript and I need to create a program that displays the current date and time in this format:
Current Date: November 16, 2013 (full name format)
Current Time: hh:mm:ss PM (12-hour clock format with AM/PM)
I am building a webpage for a friend and I'm kinda lost :/ I would appreciate any help very much. Thank you!
You can use the method date to get the current date, new Date() then use some if else blocks to change its visibility.
The basic code is as
var date = "Date is: ";
var newDate = new Date(); // get the method
date += (newDate.getMonth() + 1) + "/"; // add 1 to the result and a backslash
date += newDate.getDate() + "/"; // get today's date and a backslash
date += newDate.getFullYear(); // get the full year (2013)
document.write(date); // write this to the document
You can add some If else blocks as
if(month == "1") {
month = "January";
}
You need to work out with the API and style it, no API can do every thing for you. You need to add some code to it to make it work for you!
Good luck.
http://jsfiddle.net/afzaal_ahmad_zeeshan/k63PE/ fiddle for this

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