I have dates in JSON which are generated from ASP.NET pages using the JSON.NET library. These dates look like this:
"LastModifiedDate": "\/Date(1301412877000-0400)\/"
How do I parse these with ActionScript from Flex 3 Professional? I'd like to have this in a native data format.
NOTE: What I'm not asking here is how do I parse a JSON feed with as3corelib. I have the JSON deserialized with that library but the dates are not decoded. That is why I need to know how to decode this date format.
You'll want to use as3corelib's JSON implementation to decode your string into Objects.
/**
* Converts 'Unix tick' format JSON Date to AS3 Date instances.
* Example json input: "{\"BarDate\":\"\/Date(1334672700000)\/\" }"
* Example json input: "{\"BarDate\":\"\/Date(1334672700000+0000)\/\" }"
*
* #param json date from JSON
* #return Date if conversion possible and worked else null.
*/
public static function parseJSONUnixTickDateToDate(json:String):Date
{
var date:Date = null;
if (json)
{
json = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
var arr:Array = json.split("+");
date = new Date(Number(arr[0]));
}
return date;
}
In ASP I use this function to get a Json date
public static double JsonTime(DateTime dt)
{//Convert datetime to a Json Datetime
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);
}
and then in JavaScript I use:
if (data.indexOf("\/Date(")==7)
return new Date(+data.replace(/\D/g, ''));
to convert back to a date if that helps
You will also have fun with single and double quotes but for the life of me I can not find a decoder that works server side with Json strings on Net Framework 3!
if you use String ="\u0027" in your code then the string is already converted and in the end I wrote a function that about does the job using a loop.
string Padding = "000";
for (int f = 1; f <= 256; f++)
{
string Hex = "\\u" + Padding.Substring(0, 4 - f.ToString().Length) + f;
string Dec = "&#" + Int32.Parse(f.ToString(), NumberStyles.HexNumber) + ";";
HTML = HTML.Replace(Hex, Dec);
}
HTML = System.Web.HttpUtility.HtmlDecode(HTML);
Bad I know but if you have a better answer then please let me know!
Related
I am trying to add dynamic number of months to a date using groovy. I have tried it using TimeCategory.
I have tried as mentioned in the blog here -
[https://stackoverflow.com/questions/31707460/how-to-add-year-or-months-from-current-date-in-groovy]
However my below code dosent return correct output.
Need help to figure out what's wrong with my code.
My Input - CurrentRunDate = 2022-09-19, additionalmonths = 5
Current output from above code - MM/dd/yyyy5 months
import com.sap.it.api.mapping.*;
import java.text.SimpleDateFormat;
import groovy.time.TimeCategory
def String AddMonthsToDate(String CurrentRunDate, int additionalmonths){
def emptydate = "";
if(CurrentRunDate == "")
{
return emptydate;
}
else
{
use(TimeCategory) {
def currentdate = CurrentRunDate.format("MM/dd/yyyy")
def addmonths = currentdate + additionalmonths.month
return addmonths
}
}}
The issue here is that you are not converting CurrentRunDate into a Date object before using it with TimeCategory. You need to parse the date string, add the months you want, and then convert the Date back into a String to return.
In essence, you'll want something similar to this:
import java.text.SimpleDateFormat
import groovy.time.TimeCategory
String addMonthsToDate(String currentRunDate, int additionalMonths) {
// validate currentRunDate as being present and truthy
if (!currentRunDate) {
return ""
}
// lets set up our simple date format object for parsing and formating
def sdf = new SimpleDateFormat("MM/dd/yyyy")
// using that formmater let's parse the date string into a date obj
def parsedDate = sdf.parse(currentRunDate)
// let's now use that date obj in the TimeCategory body
def datePlusOneMonth = use(TimeCategory) { parsedDate + additionalMonths.month }
// let's convert back to a string
return sdf.format(datePlusOneMonth)
}
As a test:
assert addMonthsToDate("01/01/2000", 1) == "02/01/2000"
I am fetching datetime from an Oracle database and parsing in Java 11 using ZonedDateTime as below:
Oracle --> 1/19/2020 06:09:46.038631 PM
Java ZonedDateTime output --> 2020-01-19T18:09:46.038631Z[UTC]
Oracle --> 1/19/2011 4:00:00.000000 AM
Java ZonedDateTime output --> 2011-01-19T04:00Z[UTC] (So, here the 0s are truncated by default.
However, my requirement is to have consistent fixed length output like #1.)
Expected Java ZonedDateTime output --> 2011-01-19T04:00:00.000000Z[UTC]
However, I didn’t find any date API methods to achieve above expected output. Instead of manipulating a string, is there a way to preserve the trailing 0s with fixed length?
We have consistent ZonedDateTime types in the application, so we do not prefer to change that.
We have consistent ZonedDateTime type in application, so we do not
prefer to change that.
Why do you think 2011-01-19T04:00Z[UTC] is inconsistent? A date-time object is supposed to hold (and provide methods/functions to operate with) only the date, time, and time-zone information. It is not supposed to store any formatting information; otherwise, it will violate the Single-responsibility principle. The formatting should be handled by a formating class e.g. DateTimeFormatter (for modern date-time API), DateFormat (for legacy java.util date-time API) etc.
Every class is supposed to override the toString() function; otherwise, Object#toString will be returned when its object will be printed. A ZonedDateTime has date, time and time-zone information. Given below is how its toString() for time-part has been implemented:
#Override
public String toString() {
StringBuilder buf = new StringBuilder(18);
int hourValue = hour;
int minuteValue = minute;
int secondValue = second;
int nanoValue = nano;
buf.append(hourValue < 10 ? "0" : "").append(hourValue)
.append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
if (secondValue > 0 || nanoValue > 0) {
buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
if (nanoValue > 0) {
buf.append('.');
if (nanoValue % 1000_000 == 0) {
buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
} else if (nanoValue % 1000 == 0) {
buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
} else {
buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
}
}
}
return buf.toString();
}
As you can see, the second and nano parts are included in the returned string only when they are greater than 0. It means that you need to use a formatting class if you want these (second and nano) zeros in the output string. Given below is an example:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String input = "1/19/2011 4:00:00.000000 AM";
// Formatter for input string
DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("M/d/u H:m:s.n a")
.toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = LocalDateTime.parse(input, inputFormatter).atZone(ZoneOffset.UTC);
// Print `zdt` in default format i.e. the string returned by `zdt.toString()`
System.out.println(zdt);
// Formatter for input string
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.nnnnnnz");
String output = zdt.format(outputFormatter);
System.out.println(output);
}
}
Output:
2011-01-19T04:00Z
2011-01-19T04:00:00.000000Z
Food for thought:
public class Main {
public static void main(String[] args) {
double d = 5.0000;
System.out.println(d);
}
}
What output do you expect from the code given above? Does 5.0 represent a value different from 5.0000? How will you print 5.0000? [Hint: Check String#format, NumberFormat, BigDecimal etc.]
I am getting a date string from the javascript and converting that to Datetime and save that to the database.
But in the Indian server my code working fine. But when I upload my code to US based server it's giving exception. Is there any common way to make my code runnable to all the server.
My code is like below
[WebMethod(EnableSession = true)]
public static bool submitDate( string date ) // format is dd-mm-yyyy 20-01-2011
{
DateTime DOBdate = DateTime.Now;
double age = 0.0;
if (DateTime.TryParse(date , out DOBdate))
{
age = (DateTime.Now - DOBdate).Days / 365;
}
dbcmd.Parameters.Add("#DateOfBirth", SqlDbType.DateTime).Value = Convert.ToDateTime(DOBdate);
}
Please help me.
the exception which is showing is
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
You should use TryParseExact, I guess the default datetime format of the server is not dd-mm-yyyy. And you should handle the if of the parse function:
public static bool submitDate( string date ) // format is dd-mm-yyyy 20-01-2011
{
DateTime DOBdate = DateTime.Now;
double age = 0.0;
if (DateTime.TryParseExact(date , {"dd-MM-yyyy"},
null,
DateTimeStyles.None,
out DOBdate))
{
age = (DateTime.Now - DOBdate).Days / 365;
}
else
{
// Handle this case!
}
dbcmd.Parameters.Add("#DateOfBirth", SqlDbType.DateTime).Value = Convert.ToDateTime(DOBdate);
}
BTW your age function is not a realy good indication of the age. The older your person, the more faulty it gets.
Following my first post:
DateTime conversions using NodaTime on ASP.Net MVC 3 Razor website. How to?
I'm struggling to find an easy way to convert date/time between local and UTC (both ways), using NodaTime.
The current picture is:
I have the date/time saved as UTC in the database.
When displaying it to the user, I should consider the local time zone and convert it accordingly.
When the user provides date/time as a filter, I need to convert it back to UTC before sending to the SQL query.
What I have so far:
Extension to convert from UTC to local (this part is working fine):
public static DateTime UTCtoLocal(this DateTime dateTime)
{
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
var utcTimeZone = timeZoneProvider["UTC"];
var dateTimeFromDb = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
var zonedDbDateTime = utcTimeZone.AtLeniently(LocalDateTime.FromDateTime(dateTimeFromDb));
var usersTimezoneId = "Europe/London"; //just an example
var usersTimezone = timeZoneProvider[usersTimezoneId];
var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);
return usersZonedDateTime.ToDateTimeUnspecified();
}
Extension to convert from local back to UTC (this part is the problem):
public static DateTime LocaltoUTC(this DateTime dateTime)
{
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
var usersTimezoneId = "Europe/London";
var usersTimezone = timeZoneProvider[usersTimezoneId];
var dateTimeFromDb = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
var zonedDbDateTime = usersTimezone.AtLeniently(LocalDateTime.FromDateTime(dateTimeFromDb));
var utcTimezoneId = "UTC";
var utcTimezone = timeZoneProvider[utcTimezoneId];
var utcZonedDateTime = zonedDbDateTime.WithZone(utcTimezone);
return utcZonedDateTime.ToDateTimeUtc();
}
What am I doing wrong here?
Your UTCToLocal looks like it's doing more work than it needs to, to be honest.
It should just be:
// Note: the DateTime here must have a "Kind" of Utc.
public static DateTime UTCtoLocal(this DateTime dateTime)
{
Instant instant = Instant.FromDateTimeUtc(dateTime);
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
var usersTimezoneId = "Europe/London"; //just an example
var usersTimezone = timeZoneProvider[usersTimezoneId];
var usersZonedDateTime = instant.InZone(usersTimezone);
return usersZonedDateTime.ToDateTimeUnspecified();
}
Similarly your LocalToUTC should be along these lines:
// The DateTime here should have a "Kind" of Unspecified
public static DateTime LocaltoUTC(this DateTime dateTime)
{
LocalDateTime localDateTime = LocalDateTime.FromDateTime(dateTime);
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
var usersTimezoneId = "Europe/London";
var usersTimezone = timeZoneProvider[usersTimezoneId];
var zonedDbDateTime = usersTimezone.AtLeniently(localDateTime);
return zonedDbDateTime.ToDateTimeUtc();
}
You don't need to convert it to a different time zone: ZonedDateTime knows what the instant is, and ToDateTimeUtc will do the right thing. Note that there's no real dateTimeFromDb here, because if you're converting from an unspecified DateTime, that's presumably from the user...
I am creating an API/web service which needs to return JSON format.
I also need to create the web service as a POST request
Sample code below, see more snippets of the source code in the end of this post.
Meta meta = new Meta();
meta.recipes = new List<Recipe>();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(meta);
return strJSON;
Problem:
When I try the response in a few REST consoles (list of consoles tried) and in the ASP.NET client, I get this format with an extra "d" and extra \ before each ". See return output below:
{"d":"{\"count\":\"0\",\"status\":\"500\",\"recipes\":[]}"}
When I try to remove serialization then I get the following format:
<Meta xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns:xsd="w3.org/2001/XMLSchema"; xmlns="tempuri.org/">; <count>1</count> <status>200</status> <recipes> <Recipe> <recipeID>1</recipeID> <recipeName>Apple Pie</recipeName> <imageURL>service/it.jpg</imageURL> <rating/> </Recipe> </recipes> </Meta>
But I want it in the following format:
{"count":"0","status":"500","recipes":[]}
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public Meta RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId)
This still returns XML even though I return meta object and don't add serialization
Questions:
I thought the correct JSON format should be WITHOUT this "d" and the . Is this true or is the correct JSON format of the output actually WITH the "d" and the \?
If it should be without, then where do you suggest the correction should be made, on the server side or in the client side?
How should I correct this on the server side?
How can this be corrected on the client side?
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public string RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId,
string occasionId, string considerationId, string recipeType, string readyTime, string favouritebyUserId, string bookmarkbyUserId)
{
DataSet ds = new DataSet();
int rTime = 0;
if (readyTime == "") rTime = 0;
else rTime = Convert.ToInt32(readyTime);
ds = RecipeBLL.SearchRecipe(ingredientId, cuisineId, dishTypeId, courseId, occasionId, considerationId, recipeType, rTime);
// Create a multidimensional jagged array
string[][] JaggedArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
Meta meta = new Meta();
int count = 0;
meta.recipes = new List<Recipe>();
foreach (DataRow rs in ds.Tables[0].Rows)
{
Recipe recipe = new Recipe {
recipeID = rs["RecipeId"].ToString(),
recipeName = rs["RecipeTitle"].ToString(),
imageURL = rs["Photo"].ToString(),
rating = rs["Rating"].ToString()
};
meta.recipes.Add(recipe);
//mlist.Add(recipe);
count++;
}
if (count != 0)
meta.status = "200";
else
meta.status = "500";
meta.count = count.ToString();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON1 = js.Serialize(meta);
return strJSON1;
}
It sounds like the problem is that you're returning a string from your code somewhere - and then it's being encoded as JSON by something else. So the string you're returning is:
{"count":"0","status":"500","recipes":[]}
... but whatever you're returning from thinks you're trying to return a string, rather than an object with a count etc.
You haven't shown any of your code, but I suspect the answer will be to just remove one explicit serialization call.